[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 };

 

posted on 2017-02-14 12:34  ivancjw  阅读(960)  评论(0编辑  收藏  举报

导航