[LeetCode 493] Reverse Pairs

这道题可以用D&C或者BST做。在contest上看到一种bit manip解法,记录一下。

基本思想:

将a按lowbit减,b按lowbit加。

1. 若a >= b,则必在某点相遇(包括自身),且仅相遇一次;

2. 若a < b,永不相遇。

复杂度:

1. 期望时间复杂度是O(n),但是由于常数较大,LC测试效果不如D&C和BST解法;

2. 使用了unordered_map,较浪费内存,可能出现MLE。

 1 class Solution {
 2 public:
 3     int reversePairs(vector<int>& nums) {
 4         int res = 0;
 5         int n = nums.size();
 6         for (int i = n - 1; i >= 0; i--) {
 7             res += query((long long)nums[i] - 1);
 8             add((long long)nums[i] * 2);
 9         }
10         return res;
11     }
12     
13 private:
14     void add(long long x) {
15         for (x += 1LL << 34; x <= 1LL << 36; x += lowbit(x)) {
16             bit[x]++;
17         }
18     }
19 
20     int query(long long x) {
21         int cnt = 0;
22         for (x += 1LL << 34; x != 0; x -= lowbit(x)) {
23             if (bit.count(x)) cnt += bit[x];
24         }
25         return cnt;
26     }
27     
28     long long lowbit(long long x) {
29         return x & (-x);
30     }
31 
32 private:
33     unordered_map<long long, int> bit;
34 };

 

转载于:https://www.cnblogs.com/ivancjw/p/6397098.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值