493 Reverse Pairs

Given an array nums, we call (i, j) an important flip pair if i < j and nums[i] > 2*nums[j].
You need to return the number of significant flipped pairs in the given array.
Example 1:
Input: [1,3,2,3,1]
Output: 2
Example 2:
Input: [2,4,3,5,1]
Output: 3
Note:
    The length of the given array will not exceed 50000.
    All numbers in the input array are within the representation range of 32-bit integers.
See: https://leetcode.com/problems/reverse-pairs/description/

C++:

class Solution {
public:
    int reversePairs(vector<int>& nums) {
        int n = nums.size();
        if(n <= 1)
        {
            return 0;       
        }
        int cnt = 0;
        vector<int> b(nums.begin(), nums.begin() + n / 2);
        vector<int> c(nums.begin() + n / 2, nums.end());
        cnt += reversePairs(b);
        cnt += reversePairs(c);
        int ai = 0, bi = 0, ci = 0;
        while(ai < n)
        {
            if(bi < b.size() && (ci == c.size() || b[bi] <= c[ci]))
            {
                nums [ai ++] = b [bi ++];
            }
            else
            {
                long tmp2 = (long)c[ci]*2;
                int low = 0,high = b.size() - 1,pos = bi;
                while(low <= high)
                {
                    pos = (low + high)/2;
                    if((long)b[pos] == tmp2)
                    {
                        low++;
                    }
                    else if((long)b[pos] > tmp2)
                    {
                        high = pos - 1;
                    }
                    else
                    {
                        low = pos + 1;
                    }
                }
                if(low < b.size() && low >= 0 && (long)b[low] > tmp2)
                {
                    cnt += n/2 - low;
                }
                nums[ai++] = c[ci++];
            }
        }
        return cnt;
    }
};

 Reference: https://blog.csdn.net/lin360580306/article/details/60326795

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324609226&siteId=291194637