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
}
相关推荐
lvwangshu5 小时前
P12960 毒药 题解
动态规划·题解·贪心·技巧·性质题·思维好题
ttwuai6 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
codeejun6 天前
每日一Go·MySQL-5、锁机制全解析
云原生·golang
旖旎夜光6 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
Achou.Wang6 天前
k8s中nginx worker process自动设置
后端·golang
CoderYanger6 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂6 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_106 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_36 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z6 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode