493. Reverse Pairs
Hard
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.
class Solution { public int reversePairs(int[] nums) { int n = nums.length; return helper(nums, 0, n-1); } int helper(int[] nums, int start, int end){ if(end-start+1<2) return 0; int mid = (start+end)/2; int ret = helper(nums, start, mid); ret += helper(nums, mid+1, end); int j = mid+1, k = mid+1, t = 0; int[] cache = new int[end-start+1]; for(int i=start; i<=mid; ++i){ while(j<=end && (long)2*nums[j]<(long)nums[i]) j++; ret += j-mid-1; while(k<=end && nums[k]<=nums[i]) cache[t++] = nums[k++]; cache[t++] = nums[i]; } System.arraycopy(cache, 0, nums, start, t); return ret; } }
No comments:
Post a Comment