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
}
相关推荐
运筹vivo@9 小时前
2657. 找到两个数组的前缀公共数组 | 难度:中等
算法·leetcode·职场和发展·哈希表
比特森林探险记9 小时前
go 语言中的context 解读和用法
开发语言·后端·golang
叶小鸡15 小时前
小鸡玩算法-力扣HOT100-动态规划(下)
算法·leetcode·动态规划
毅炼17 小时前
今日LeetCode 摸鱼打卡
java·算法·leetcode
m0_6294947317 小时前
LeetCode 热题 100-----28. 两数相加
数据结构·算法·leetcode·链表
菜菜的顾清寒17 小时前
力扣HOT100(25)环形链表
算法·leetcode·链表
jieyucx19 小时前
从基础语法到面向对象:Go语言如何实现封装、继承与多态?
开发语言·后端·golang
littleschemer21 小时前
Go:实现游戏服务器网关
服务器·网关·游戏·golang
Controller-Inversion21 小时前
76. 最小覆盖子串
java·算法·leetcode
_日拱一卒21 小时前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展