[leetcode]493. Reverse Pairs

链接:https://leetcode.com/problems/reverse-pairs/description/

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.

Example1:

Input: [1,3,2,3,1]
Output: 2

Example2:

Input: [2,4,3,5,1]
Output: 3

class Solution {
public:
    int reversePairs(vector<int>& nums) {
        return sort_and_count(nums.begin(),nums.end());
    }
    
    int sort_and_count(vector<int>::iterator begin,vector<int>::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 && *i>2L * (*j))
                j++;
            count+=j-mid;
        }
        inplace_merge(begin,mid,end);
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaocong1990/article/details/80671201
今日推荐