493. Reverse Pairs
阿新 • • 發佈:2020-08-01
Given an arraynums
, we call(i, j)
animportant reverse pairifi < j
andnums[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.
class Solution { public int reversePairs(int[] nums) { return help(nums, 0, nums.length - 1); } public int help(int[] nums, int lo, int hi) { if(lo >= hi) return 0; int mid = lo + (hi - lo) / 2;int res = help(nums, lo, mid) + help(nums, mid + 1, hi); Arrays.sort(nums, lo, mid + 1); Arrays.sort(nums, mid + 1, hi + 1); int i = lo; int j = mid + 1; while(i <= mid && j <= hi) { if((long) nums[i] > (long) nums[j] * 2) { res+= mid - i + 1; j++; } else i++; } return res; } }