【分治算法】Leetcode编程题解:493. Reverse Pairs Add to List

题目:

Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].

You need to return the number of important reverse pairs in the given array.


样例:
1. Input: [1,3,2,3,1]
    Output: 2
2. Input: [2,4,3,5,1]
    Output: 3
要求:
  1. The length of the given array will not exceed 50,000.
  2. All the numbers in the input array are in the range of 32-bit integer.
题目刚开始采用二分查找解决,先申请一个新的数组存储其所有值的2倍,排序,然后每一次取原数组中的值作为中间值进行查找,代码如下:
class Solution {
public:
     vector::iterator find(vector& tmp,long aim)
     {
         int a=0,b=tmp.size()-1;
         while(aaim)
                b=c-1;
             else if(tmp[c]& tmp,int a)
     {
         int begin=0,end=tmp.size()-1,middle;
         if(end<0)
            return 0;
         while(begin=a) 
            return begin;
         else
            return tmp.size();
     }

    int reversePairs(vector& nums) {
        int n=nums.size();
        vectortmp(n,0);
        for(int i=0;i::iterator iter=find(tmp,aim);  
            tmp.erase(iter);
            ans+=count(tmp,nums[i]);

        }
        return ans;

    }
};
但是超时,所以参考已通过的代码,采用归并排序解决,以下为摘抄:
Just a mergesort solution, but using iterators (instead of indexes) and inplace_merge.
class Solution {
public:
    int sort_and_count(vector::iterator begin, vector::iterator end) {
        if (end - begin <= 1)
            return 0;
        auto mid = begin + (end - begin) / 2;
        int count = sort_and_count(begin, mid) + sort_and_count(mid, end);
        for (auto i = begin, j = mid; i != mid; ++i) {
            while (j != end and *i > 2L * *j)
                ++j;
            count += j - mid;
        }
        inplace_merge(begin, mid, end);
        return count;
    }

    int reversePairs(vector& nums) {
        return sort_and_count(nums.begin(), nums.end());
    }
};

你可能感兴趣的:(Leetcode解题报告)