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
Note:
- The length of the given array will not exceed
50,000. - All the numbers in the input array are in the range of 32-bit integer.
题目链接:https://leetcode-cn.com/problems/reverse-pairs/
思路
用归并排序的思路,不断向下划分到小区间,因为merge的2段都是有序的,因此找逆序快,每次merge只看当前的逆序数量,向上再不断累加。
class Solution {
public:
int reversePairs(vector<int>& nums) {
int len = nums.size();
if(len<=1) return 0;
vector<int> tmp(len);
return sort(nums, tmp, 0, len-1);
}
int sort(vector<int> &nums, vector<int> &temp, int l, int r){
if(l>=r) return 0;
int mid = l + (r-l)/2;
int sum = sort(nums, temp, l, mid) + sort(nums, temp, mid+1, r);
//merge
int l1 = l, l2 = mid+1;
while(l1<=mid && l2<=r){
if((long)nums[l1] > (long)nums[l2]*2){
sum += (mid-l1+1);
++l2;
}else{
++l1;
}
}
//sort
int idx=0;
l1 = l;
l2 = mid+1;
while(l1<=mid && l2<=r){
if(nums[l1]<=nums[l2]){
temp[idx++] = nums[l1++];
}else{
temp[idx++] = nums[l2++];
}
}
while(l1<=mid){
temp[idx++] = nums[l1++];
}
while(l2<=r){
temp[idx++] = nums[l2++];
}
for(int i=l; i<=r; ++i){
nums[i] = temp[i-l];
}
return sum;
}
};

本文详细解析了LeetCode上的493题——逆序对问题,介绍了如何使用归并排序的思想来高效地解决这一问题。通过将数组不断划分成小的区间,并利用归并过程中的有序特性,快速找到所有逆序对,最终返回逆序对的数量。
885

被折叠的 条评论
为什么被折叠?



