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
}
相关推荐
Hi李耶11 分钟前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
Hi李耶4 小时前
【LeetCode】6-Z字形变换
算法·leetcode·职场和发展
AKA__Zas4 小时前
芝士算法(前缀和2.0)
java·数据结构·算法·leetcode·哈希算法·学习方法
皓月斯语4 小时前
B3867 [GESP202309 三级] 小杨的储蓄 题解
c++·算法·题解
techdashen4 小时前
Go设计取舍之三: 0.3ns每次的错误Benchmark
开发语言·后端·golang
闪电悠米5 小时前
力扣hot100-142.环形链表II-哈希集合与快慢指针详解
leetcode·链表·哈希算法
Tisfy5 小时前
LeetCode 0486.预测赢家:深度优先搜索(DFS)
算法·leetcode·深度优先·dfs·博弈
techdashen6 小时前
Go设计取舍之四: map不变时能否并发修改不同value
开发语言·后端·golang
退休倒计时6 小时前
【每日一题】LeetCode 45. 跳跃游戏 II TypeScript
算法·leetcode·typescript
名字还没想好☜7 小时前
Go 表驱动测试实战:用 t.Run 子测试组织可维护的单元测试
golang·单元测试·log4j·go·testing