Reverse Pairs

For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.

Example

Given A = [2, 4, 1, 3, 5] , (2, 1), (4, 1), (4, 3) are reverse pairs. return 3

分析:

如果用两个for loop,非常简单。但要降低复杂度,做法非常变态.简单来说,原理就是利用merge sort的方法,把左subarray 和右subarray 合并(假设它们都已排好序)。然后比较当前左subarray的第一个值是否比右边subarray第一个值大两倍,如果是,那么很明显左subarray所有的都比那个值大两倍。

 1 class Solution {
 2     public int reversePairs(int[] nums) {
 3         return mergeSort(nums, 0, nums.length - 1);
 4     }
 5     
 6     public int mergeSort(int[] nums, int start, int end) {
 7         if (start >= end) return 0;
 8         int total =  0;
 9         int mid = start + (end - start) / 2;
10         total += mergeSort(nums, start, mid);
11         total += mergeSort(nums, mid + 1, end);
12         total += merge(nums, start, mid, end);
13         return total;
14     }
15 
16     public int merge(int[] nums, int start, int mid, int end) {
17         int[] temp = new int[end - start + 1];
18         int p1 = start, p2 = mid + 1;
19         int index = 0,count = 0;
20         
21         while (p1 <= mid && p2 <= end) {
22             if ((long) nums[p1] > 2 * ((long) nums[p2])) {
23                 count += mid - p1 + 1;
24                 p2++;
25             } else {
26                 p1++;
27             }
28         }
29         p1 = start;
30         p2 = mid + 1;
31         while (p1 <= mid && p2 <= end) {
32             if (nums[p1] < nums[p2]) {
33                 temp[index++] = nums[p1++];
34             } else {
35                 temp[index++] = nums[p2++];
36             }
37         }
38         
39         while(p1 <= mid) {
40             temp[index++] = nums[p1++];
41         }
42         while(p2 <= end) {
43             temp[index++] = nums[p2++];
44         }
45         System.arraycopy(temp, 0, nums, start, end - start + 1);
46         return count;
47     }
48 }

 

 

posted @ 2016-07-06 02:01  北叶青藤  阅读(212)  评论(0编辑  收藏  举报