51. The array face questions on reverse --leecode

51. The array face questions to reverse

Two numbers in the array, if a number is greater than the front behind the figures, the two numbers form a reverse pair. Enter an array, the total number of this array is determined to reverse.
Topic Link

Thinking

Fenwick tree to use to solve the problem. To make the data represent a reasonable range, but also to be discrete.

Code

This question is most likely that the pit array where there are duplicate numbers, for example, [1,3,2,1,2], the weight must go, then discretized. According to the following order after discrete subject to insert Fenwick tree, recount results.

class Solution {
public:
    lowbit(int x){
        return (x & -x);
    }
    int query(int tar,vector<int> &c){
        int ans = 0;
        while(tar > 0){
            ans += c[tar];
            tar -= lowbit(tar);
        }
        return ans;
    }
    void update(int tar,int l,vector<int> &c){
        while(tar <= l){
            c[tar]++;
            tar += lowbit(tar);
              
        }
    }
    int reversePairs(vector<int>& nums) {
        vector<int> c(nums.size() + 10,0);
        int l = nums.size(),ans = 0;
        vector<int> temp(nums);
        //排序
        sort(temp.begin(),temp.end());
        //去重!!!
        temp.erase(unique(temp.begin(),temp.end()),temp.end());
        map<int,int> arr;
        for(int i = 0;i < temp.size();i++){
            arr.insert(pair<int,int>(temp[i],i + 1));
        }
        //更新
        for(int i = 1;i <= l;i++){
            int tar = arr[nums[i - 1]];
            update(tar,l,c);
            ans += i - query(tar,c);
        }
        return ans;  
    }
};
Released three original articles · won praise 0 · Views 30

Guess you like

Origin blog.csdn.net/free1993/article/details/104338366