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
}
相关推荐
漂流瓶jz6 小时前
UVA-1442 洞穴 题解答案代码 算法竞赛入门经典第二版
c++·算法·题解·aoapc·算法竞赛入门经典·uva
圣保罗的大教堂6 小时前
leetcode 835. 图像重叠 中等
leetcode
五彩小白10 小时前
GO语言装饰器语法
golang
wabs66610 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin0310 小时前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
0+11112 小时前
算法 --滑动窗口
c++·算法·leetcode
木井巳14 小时前
【记忆化搜索】最长递增子序列
java·算法·leetcode·深度优先·剪枝·推荐算法
圣保罗的大教堂16 小时前
leetcode 1401. 圆和矩形是否有重叠 中等
leetcode
金金计较.16 小时前
Go语言-4
开发语言·golang
hanlin0316 小时前
刷题笔记:力扣第76题-最小覆盖子串
笔记·算法·leetcode