Reverse Pairs

Reverse Pairs

Description:

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

分析:

这道题有两种思路,

思路一

就是Merge Sort的思想。

思路二

可以这样想,找右边比左边小的数字的个数,可以先对包括当前数字在内以及它右边的所有数字进行非降序排序(所以需要从最后一个开始),如果每次排序都保证当前数字在排序结果中的位置的左边都是比它小的值(与当前数字相等的数字放到当前数字的右边),那么比当前的数字小的一定都在当前数字的左边,则它的索引就是原数组中在当前数字的右边且比它小的数字的个数。

实现上,排序使用类似二叉查找的方法(时间复杂度是O(lgn))思路是将给定数组从最后一个开始,用二分法插入到一个新的数组,这样新数组就是有序的。注意这里的返回条件是left<right不成立的时候。

 

代码如下:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
/**
* @param A an array
* @return total of reverse pairs
*/
long long reversePairs(vector<int>& A) {
// Write your code here
vector<int> temp(A.size(), 0);
return mergeSortVarity(A, temp, 0, A.size() - 1);
}

int mergeSortVarity(vector<int>& A, vector<int>& temp, int left, int right) {
int mid, inv_count = 0;
if (left < right) {
mid = left + (right - left)/2;

inv_count = mergeSortVarity(A, temp, left, mid);
inv_count += mergeSortVarity(A, temp, mid+1, right);

inv_count += merge(A, temp, left, mid+1, right);
}
return inv_count;
}

int merge(vector<int>& A, vector<int>& temp, int left, int mid, int right) {
int i, j, k;
int inv_count = 0;

i = left;
j = mid;
k = left;
while ((i <= mid - 1) && (j <= right)) {
if (A[i] <= A[j]) {
temp[k++] = A[i++];
}
else {
temp[k++] = A[j++];

inv_count = inv_count + (mid - i);
}
}

while (i <= mid - 1)
temp[k++] = A[i++];

while (j <= right)
temp[k++] = A[j++];

for (i=left; i <= right; i++)
A[i] = temp[i];

return inv_count;
}
};

 

思路二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
/**
* @param A an array
* @return total of reverse pairs
*/
long long reversePairs(vector<int>& A) {
// Write your code here
long long res = 0;
vector<int> v;
for (int i = A.size() - 1; i >= 0; --i) {
int left = 0, right = v.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (A[i] > v[mid]) left = mid + 1;
else right = mid;
}
v.insert(v.begin() + right, A[i]);
res += right;
}
return res;
}
};