Title Description
Two numbers in the array, if a number is greater than the front behind the figures, the two numbers form a reverse pair. Enter an array, this array P. finds the total number of reverse pair P and outputs the result modulo 1000000007. I.e., the output P% 1000000007
Input Description:
Title ensure the same digital input array not in
range of data:
the data% 50, size <= 10 ^ 4
for data% 75, size <= 10 ^ 5
for data% 100, size <= 2 * 10 ^ 5
input
1,2,3,4,5,6,7,0
output
7
Ideas analysis
Encounter reverse order or decimal and such problems are based on a strategy of divide and conquer merge sort to do.
When the merge sort, the two sequences are incorporated are ordered, such as 234 incorporated 15, 2> 1 Release Number 2 are behind> 1, thus directly mid-indexOf (2) +1 to.
This problem, the results also need to take more than twice, once in the internal sorting, once when returning results because the cattle off the net test cases extremely large.
Code Analysis
public int InversePairs(int[] array) {
if (array == null || array.length < 2) {
return 0;
}
return mergeSort(array, 0, array.length - 1);
}
private int mergeSort(int[] array, int left, int right) {
if (left == right) {
return 0;
}
int mid = left + (right - left) / 2;
return (mergeSort(array, left, mid) +
mergeSort(array, mid + 1, right) +
merge(array, left, mid, right))%1000000007;
}
private int merge(int[] array, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int i = 0, p1 = left, p2 = mid + 1, result = 0;
while (p1 <= mid && p2 <= right) {
//并入的时候,利用有序性
result += array[p1] > array[p2] ? (mid - p1 + 1) : 0;
result = result>1000000007?result%1000000007:result;
help[i++] = array[p1] < array[p2] ? array[p1++] : array[p2++];
}
while (p1 <= mid) {
help[i++] = array[p1++];
}
while (p2 <= right) {
help[i++] = array[p2++];
}
for (int j = 0; j < help.length; j++) {
array[left + j] = help[j];
}
return result;
}