Sword refers to offer-51. Reversed pairs in an array-analysis and code [Java]
1. Title
For two numbers in the array, if the first number is greater than the following number, the two numbers form a reverse pair. Input an array, find the total number P of reverse pairs in this array, and output the result of P modulo 1000000007. That is, P%1000000007 is output. .
Input description: The
title guarantees the same number that is not in the input array
data range:
- For %50 data, size<=10^4
- For %75 data, size<=10^5
- For %100 data, size<=2*10^5
Example 1:
input
1,2,3,4,5,6,7,0
Output
7
Two, analysis and code
1. Merge Sort
(1) Thinking
This question can be solved by combining the idea of merging and sorting: in each merging process, (assuming the sorting from small to large), when the larger number crosses the smaller back digit from the front side into a new position, the number of smaller digits exceeded is the reverse order The number of pairs.
Combined with the question prompt, the result of this question may be of a larger magnitude, which can be solved by performing a modulo operation after each accumulation.
(2) Code
public class Solution {
public int InversePairs(int [] array) {
if (array == null || array.length == 0)
return 0;
return Sort(array, 0, array.length);
}
public int Sort(int[] array, int left, int right) {
if (right - left < 2)
return 0;
int mid = (left + right) >> 1;
int num = 0;
num += Sort(array, left, mid);
num += Sort(array, mid, right);
int [] tempArray = new int[right - left];
int l = left, r = mid;
for (int i = left; i < right; i++) {
if (r == right || (l < mid && array[l] < array[r])) {
tempArray[i - left] = array[l++];
} else {
tempArray[i - left] = array[r++];
num += mid - l;
num %= 1000000007;
}
}
for (int i = left; i < right; i++)
array[i] = tempArray[i - left];
return num;
}
}
(3) Results
Running time: 464ms, occupied memory: 50408k.
Three, other
Nothing.