The inverse of the array describes the topic
In the array of two digits, if the previous number is greater than the number that follows, then these two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in this array.
Ideas
- If the entire array is scanned, each number is larger than the number that follows, and the overall complexity is O (n^2)
- Can use the idea of the algorithm of merging sorting, at the same time to determine the order of the two sub-sequences in reverse, are from the back to the front row, if the previous number is greater than the number behind, because it is already in the order of the previous number is larger than the number of the following, reverse order for the remainder of the number of elements, and , then this element does not produce reverse order, normal ordering. Time complexity is O (NLOGN)
Code
PublicClass Solution {PublicIntInversepairs(int []Array) {if (Array = = NULL | |Array.Length = =0) {Return0; }int[] Copy =Newint[Array.Length];for (int i =0; I <Array.Length; i++) {Copy[i] =Array[i]; }int count = Inversecore (Array, copy,0,Array.Length-1);return count; }PublicIntInversecore(int[] Data,int[] Copy,int start,int end) {if (start = = end) {Copy[start] = Data[start];Return0; }int length = (end-start)/2;int left = Inversecore (copy, data, start, start + length);int right = Inversecore (copy, data, start + length + 1, end); int i = start + length; int j = end; int indexcopy = end; int count = 0; while (i >= start && J >= start + length + 1) {if (Data[i] > Data[j]) {copy[indexcopy--] = data[i--]; count + = J-(start + length);} else {copy[indexcopy--] = data[j--];}} for (; I >= start; i--) {copy[indexcopy--] = data[i];} for (; J >= Start+length+1; j--) {copy[indexcopy--] = data[j];} return count + left + right;}}
Reverse order in array--sword point offer