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
}
相关推荐
逆境不可逃4 小时前
LeetCode 热题 100 之 64. 最小路径和 5. 最长回文子串 1143. 最长公共子序列 72. 编辑距离
算法·leetcode·动态规划
yashuk4 小时前
Go-Gin Web 框架完整教程
前端·golang·gin
Eward-an5 小时前
LeetCode 239. 滑动窗口最大值(详细技术解析)
python·算法·leetcode
一叶落4385 小时前
LeetCode 50. Pow(x, n)(快速幂详解 | C语言实现)
c语言·算法·leetcode
x_xbx7 小时前
LeetCode:26. 删除有序数组中的重复项
数据结构·算法·leetcode
j_xxx404_8 小时前
力扣困难算法精解:串联所有单词的子串与最小覆盖子串
java·开发语言·c++·算法·leetcode·哈希算法
big_rabbit05028 小时前
[算法][力扣167]Two Sum II
算法·leetcode·职场和发展
Eward-an9 小时前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展
不想看见40410 小时前
Reverse Bits位运算基础问题--力扣101算法题解笔记
笔记·算法·leetcode
逆境不可逃10 小时前
LeetCode 热题 100 之 394. 字符串解码 739. 每日温度 84. 柱状图中的最大矩形
算法·leetcode·职场和发展