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
}
相关推荐
姚不倒7 小时前
Go语言进阶:接口、错误处理与并发编程(goroutine/channel/context)
云原生·golang
失去的青春---夕阳下的奔跑10 小时前
560. 和为 K 的子数组
数据结构·算法·leetcode
m0_6294947311 小时前
LeetCode 热题 100-----25.回文链表
数据结构·算法·leetcode·链表
吃着火锅x唱着歌13 小时前
LeetCode 1019.链表中的下一个更大节点
算法·leetcode·链表
凌波粒14 小时前
LeetCode--404.左叶子之和(二叉树)
算法·leetcode·职场和发展
绝知此事14 小时前
【算法突围 03】核心算法思想:分治/递归/动态规划与 LeetCode 高频真题解析
算法·leetcode·面试·动态规划
宇明一不急14 小时前
go 链表 (标准库实现)
开发语言·链表·golang
阿Y加油吧16 小时前
两道字符串 DP 模板题复盘:最长公共子序列 & 编辑距离
leetcode
~|Bernard|16 小时前
GO语言中哪些类型是可比较类型的(==和!=)
开发语言·后端·golang
我爱cope16 小时前
【力扣hot100:76. 最小覆盖子串】
算法·leetcode·职场和发展