For two numbers in the array, if the previous number is greater than the latter number, the two numbers form a reverse order pair. For example, in the array {7, 5, 6, 4}, there are a total of 5 reverse order pairs, which are {7, 6}, {7, 5}, {7, 4}, {6, 4}, {5, 4}. Input an array, find the total number P of inverse pairs in this array. And output the result of P modulo 1000000007. , that is, output P%1000000007.
code
Solution one
Violence is simple and inefficient, and will not change the original array
public static int inversePairs(int[] array) { if (array == null || array.length < 2) { return 0; } int count = 0; for (int i = 0; i < array.length; i++) { for (int j = i + 1; j < array.length; j++) { if (array[i] > array[j]) { count++; } } } return count % 1000000007; }
Solution two
Use the merge sort of the array, which is efficient, but will change the original array
public static int inversePairs2(int[] array) { if (array == null || array.length < 2) { return 0; } int count = mergeSort(array, 0, array.length - 1); return count % 1000000007; } private static int mergeSort(int[] array, int start, int end) { if (start >= end) { return 0; } // Find the midpoint of the array, split it into two sub-arrays, and solve it recursively int middle = (start + end) / 2; int left = mergeSort(array, start, middle); int right = mergeSort(array, middle + 1, end); // store the merged array int[] copy = new int[array.length]; System.arraycopy(array, start, copy, start, end - start + 1); // Start traversing from the end of the two subarrays int i = middle; int j = end; int copyIndex = end; // record the number of reverse pairs int count = 0; while (i >= start && j >= middle + 1) { // array is in ascending order // If the left array is larger than the right array, put the larger one into the storage array // And accumulate the reverse order pairs, it should be ordered, so the i-th element of the left array is larger than the j-th and previous numbers if (array[i] > array[j]) { copy[copyIndex--] = array[i--]; count += (j - middle); } else { copy[copyIndex--] = array[j--]; } } // Write the remainder of the subarray to the merged storage array once while (i >= start) { copy[copyIndex--] = array[i--]; } while (j >= middle + 1) { copy[copyIndex--] = array[j--]; } // Write the merge of the two subarrays into the original array for (int k = start; k <= end ; k++) { array[k] = copy[k]; } return left + right + count; }