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
}
相关推荐
Navigator_Z11 小时前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
lvwangshu12 小时前
登录日志 题解
数据结构·线段树·题解·技巧·性质题·思维好题·细节题
青山木14 小时前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.16 小时前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
大侠归来20 小时前
C 与 Go 语言对比:从设计哲学到工程实践
java·c语言·golang
All for pursuit.20 小时前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
小小龙学IT21 小时前
Go 语言内存管理与垃圾回收(GC)深度解析:从逃逸分析到性能调优适
golang·go1.19
漂流瓶jz1 天前
UVA-1610 聚会游戏 题解答案代码 算法竞赛入门经典第二版
数据结构·c++·算法·题解·aoapc·算法竞赛入门经典·uva
代码什么用1 天前
LeetCode-560.和为 K 的子数组
算法·leetcode
All for pursuit.1 天前
【回溯-3】39.组合总和
数据结构·c++·算法·leetcode