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
}
相关推荐
Excuse_lighttime几秒前
只出现一次的数字(位运算算法)
java·数据结构·算法·leetcode·eclipse
爱coding的橙子2 小时前
每日算法刷题Day70:10.13:leetcode 二叉树10道题,用时2h
算法·leetcode·深度优先
CoLiuRs2 小时前
异步任务使用场景与实践
微服务·性能优化·golang
poemyang16 小时前
Goroutine间的“灵魂管道”:Channel如何实现数据同步与因果传递?
golang·并发编程
Lazy龙18 小时前
Golang协程
golang
2351618 小时前
【LeetCode】146. LRU 缓存
java·后端·算法·leetcode·链表·缓存·职场和发展
tkevinjd21 小时前
反转链表及其应用(力扣2130)
数据结构·leetcode·链表
程序员烧烤1 天前
【leetcode刷题007】leetcode116、117
算法·leetcode
Swift社区1 天前
LeetCode 395 - 至少有 K 个重复字符的最长子串
算法·leetcode·职场和发展
Espresso Macchiato1 天前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167