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
}
相关推荐
Nil20812 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_6745719713 小时前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂14 小时前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin77014 小时前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao21 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1231 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi1 天前
力扣70爬楼梯
数据结构·算法·leetcode
云和数据.ChenGuang1 天前
Golang AI 工程师路线图:从入门到实战
开发语言·人工智能·后端·golang
报错小能手1 天前
内存管理 垃圾回收面试题
golang
Navigator_Z2 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode