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
| public class Solution { public int InversePairs(int [] array) { if (array==null || array.length<=0) return 0; int[] copy = new int[array.length]; for (int i=0; i<array.length; ++i) copy[i] = array[i]; long count=InversePairsCore(array, copy, 0, array.length-1); return (int)count; } public long InversePairsCore(int[] array, int[] copy, int start, int end) { if (start == end) { copy[start] = array[start]; return 0; } int length = (end-start)/2; long left = InversePairsCore(copy, array, start, start+length); long right = InversePairsCore(copy, array, start+length+1, end); int i= start + length; int j = end; int indexCopy = end; long count = 0; while (i>=start && j>=start+length+1) { if (array[i] > array[j]) { copy[indexCopy--] = array[i--]; count += j-start-length; } else { copy[indexCopy--] = array[j--]; } } for (; i>=start; --i) copy[indexCopy--] = array[i]; for (; j>=start+length+1; --j) copy[indexCopy--] = array[j]; return left+right+count; } public static void main(String[] args) { Solution solu = new Solution(); int[] a = {364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575}; System.out.println(solu.InversePairs(a)); } }
|