GuilinDev

Lc0493

05 August 2008

493. Reverse Pairs

Given an integer array nums, return the number of reverse pairs in the array.

A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].

Example 1:

Input: nums = [1,3,2,3,1] Output: 2 Example 2:

Input: nums = [2,4,3,5,1] Output: 3

Constraints:

1
2
1 <= nums.length <= 5 * 104
-231 <= nums[i] <= 231 - 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
    public int reversePairs(int[] nums) {
        return mergeSort(nums, 0, nums.length-1);
    }
    
    public int mergeSort(int[] nums, int l, int r) {
        if (l >= r) return 0;
        
        int m = l + (r - l) / 2;
        int res = mergeSort(nums, l, m) + mergeSort(nums, m+1, r);
		
        // Classic Merge Sort Approach
        int[] tmp = new int[r-l+1];
        int i = l, j = m+1, k = 0;
        while (i <= m && j <= r) {
            if (nums[i] <= nums[j]) tmp[k++] = nums[i++];
            else tmp[k++] = nums[j++];
        }
        while (i <= m) tmp[k++] = nums[i++];
        while (j <= r) tmp[k++] = nums[j++];
        
		// Count valid nums[i]
        for (i = l, j = m+1; i <= m; i++) {
            while (j <= r && nums[i] / 2.0 > nums[j]) j++;
            res += j - m - 1;
        }
        
		// Applying the sorted results to nums
			// Apply only after counting is because this would 
			// mess up the relative positions of left & right sections
        for (i = l, j = 0; i <= r; i++, j++) nums[i] = tmp[j];
        return res;
    }
}