|
| 1 | +/* |
| 2 | +Reverse Pairs |
| 3 | +============= |
| 4 | +
|
| 5 | +Given an integer array nums, return the number of reverse pairs in the array. |
| 6 | +
|
| 7 | +A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j]. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: nums = [1,3,2,3,1] |
| 11 | +Output: 2 |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input: nums = [2,4,3,5,1] |
| 15 | +Output: 3 |
| 16 | +
|
| 17 | +Constraints: |
| 18 | +1 <= nums.length <= 5 * 104 |
| 19 | +231 <= nums[i] <= 231 - 1 |
| 20 | +*/ |
| 21 | + |
| 22 | +class Solution |
| 23 | +{ |
| 24 | +public: |
| 25 | + int merge(vector<int> &nums, int low, int mid, int high) |
| 26 | + { |
| 27 | + int count = 0; |
| 28 | + int i = low, j = mid + 1; |
| 29 | + |
| 30 | + // count pairs |
| 31 | + while (i <= mid) |
| 32 | + { |
| 33 | + while (j <= high && nums[i] > 2LL * nums[j]) |
| 34 | + j++; |
| 35 | + count += (j - (mid + 1)); |
| 36 | + i++; |
| 37 | + } |
| 38 | + |
| 39 | + // merge the sorted arrays |
| 40 | + vector<int> temp; |
| 41 | + i = low; |
| 42 | + j = mid + 1; |
| 43 | + |
| 44 | + while (i <= mid && j <= high) |
| 45 | + { |
| 46 | + if (nums[i] < nums[j]) |
| 47 | + temp.push_back(nums[i++]); |
| 48 | + else |
| 49 | + temp.push_back(nums[j++]); |
| 50 | + } |
| 51 | + |
| 52 | + while (i <= mid) |
| 53 | + temp.push_back(nums[i++]); |
| 54 | + while (j <= high) |
| 55 | + temp.push_back(nums[j++]); |
| 56 | + |
| 57 | + for (int k = low; k <= high; ++k) |
| 58 | + nums[k] = temp[k - low]; |
| 59 | + |
| 60 | + return count; |
| 61 | + } |
| 62 | + |
| 63 | + int mergeSort(vector<int> &nums, int low, int high) |
| 64 | + { |
| 65 | + int count = 0; |
| 66 | + if (low < high) |
| 67 | + { |
| 68 | + int mid = (low + high) / 2; |
| 69 | + count += mergeSort(nums, low, mid); |
| 70 | + count += mergeSort(nums, mid + 1, high); |
| 71 | + count += merge(nums, low, mid, high); |
| 72 | + } |
| 73 | + return count; |
| 74 | + } |
| 75 | + |
| 76 | + int reversePairs(vector<int> &nums) |
| 77 | + { |
| 78 | + return mergeSort(nums, 0, nums.size() - 1); |
| 79 | + } |
| 80 | +}; |
0 commit comments