题目: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.
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 50,000.
- All the numbers in the input array are in the range of 32-bit integer.
思路: 这道题目让我们求出逆转对的数目,逆转对就是符合i < j&&num[i] >= 2*num[j]条件的一对元素。可以采用分而治之的思想,在每一级合并的时候,因为左右两部分的元素的相对位置没有发生变化并且都是有序的,采用双指针,在遍历左边部分的每一个元素时,在右边部分找到第一个不符合num[i] > 2 * num[j]条件的索引,j-(mid+1)就是元素num[i]在这一级的逆序对数目。最后再将左右两部分进行排序,返回上一级的同时返回这一级逆序对的总数。 代码如下:
class Solution {
public:
int reversePairs(vector<int>& nums) {
return mergeSort(nums, 0, nums.size() - 1);
}
int mergeSort(vector<int>& nums, int left, int right) {
if (left >= right) return 0;
int mid = left + (right - left) / 2;
int res = mergeSort(nums, left, mid) + mergeSort(nums, mid + 1, right);
for (int i = left, j = mid + 1; i <= mid; ++i) {
while (j <= right && nums[i] / 2.0 > nums[j]) ++j;
res += j - (mid + 1);
}
sort(nums.begin() + left, nums.begin() + right + 1);
return res;
}
};