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
}
相关推荐
笨笨没好名字1 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode
想你依然心痛1 小时前
AtomCode在后端开发中的实战体验:Go微服务从零搭建
开发语言·微服务·golang
王老师青少年编程2 小时前
2026年6月GESP真题及题解(C++五级):排排坐
c++·题解·真题·gesp·五级·2026年6月·排排坐
开发小程序的之朴2 小时前
认识安企CMS - 系统概述
nginx·golang·系统架构
雨师@2 小时前
go语言项目--实例化(图书管理)--005
开发语言·后端·golang
Vect__3 小时前
Go 数据结构 slice 深度剖析
开发语言·数据结构·golang
geovindu3 小时前
go: Functional Options Pattern
开发语言·后端·设计模式·golang·函数式选项模式’·惯用法模式
青山木3 小时前
Hot 100 --- LRU 缓存
java·数据结构·算法·leetcode·链表·缓存·哈希
王老师青少年编程4 小时前
2026年6月GESP真题及题解(C++五级):晚宴
c++·题解·真题·gesp·五级·2026年6月·晚宴
想你依然心痛4 小时前
AtomCode在算法竞赛中的实战体验:LeetCode周赛辅助编程
linux·算法·leetcode