Golang | Leetcode Golang题解之第493题翻转对

题目:

题解:

Go 复制代码
type fenwick struct {
    tree []int
}

func newFenwickTree(n int) fenwick {
    return fenwick{make([]int, n+1)}
}

func (f fenwick) add(i int) {
    for ; i < len(f.tree); i += i & -i {
        f.tree[i]++
    }
}

func (f fenwick) sum(i int) (res int) {
    for ; i > 0; i &= i - 1 {
        res += f.tree[i]
    }
    return
}

func reversePairs(nums []int) (cnt int) {
    n := len(nums)
    if n <= 1 {
        return
    }

    // 离散化所有下面统计时会出现的元素
    allNums := make([]int, 0, 2*n)
    for _, v := range nums {
        allNums = append(allNums, v, 2*v)
    }
    sort.Ints(allNums)
    k := 1
    kth := map[int]int{allNums[0]: k}
    for i := 1; i < 2*n; i++ {
        if allNums[i] != allNums[i-1] {
            k++
            kth[allNums[i]] = k
        }
    }

    t := newFenwickTree(k)
    for i, v := range nums {
        // 统计之前插入了多少个比 2*v 大的数
        cnt += i - t.sum(kth[2*v])
        t.add(kth[v])
    }
    return
}
相关推荐
evans在进步5 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil2085 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
FfHUCisI5 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang
吃着火锅x唱着歌6 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王6 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
土司大王8 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
Navigator_Z8 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs6668 小时前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
Nil2089 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
报错小能手9 小时前
Go 语言结构 基础语法
开发语言·后端·golang