Reverse pairs in an array: an alternative application of merge ordering
Inverse pairs in an array: Given an array, if the previous number in the two digits is greater than the one in the back, then it is called a reverse pair, and all the reverse pairs that satisfy the relationship in the array are the reverse of this array.
The implementation here is not elegant, after all, the copy array is not needed, only need a local can
But if you are using a local space complexity that is a LOGN auxiliary array, it can cause code to be a little hard to understand
In addition, the book is obviously the wrong code, not run, but logically analyzed, there should be duplication of statistical problems
public class _q36<t> {public int inversepairs (int nums[]) {if (nums = = null) return 0;
int copy[] = arrays.copyof (nums, nums.length);
Commonutils.printarray (copy);
Return Inversepairscore (nums, copy, 0, nums.length-1); private int Inversepairscore (int nums[], int copy[], int indexl, int indexr) {if (Nums = null | | indexl ;
INDEXR) return 0;
if (Indexl = = Indexr) {//COPY[INDEXL] = Nums[indexl];
return 0;
int len = (INDEXR-INDEXL)/2;
int leftcount = Inversepairscore (nums, copy, INDEXL, Indexl + len);
int rightcount = Inversepairscore (nums, copy, Indexl + len + 1, INDEXR);
int i = Indexl + len;
int j = INDEXR;
int indexcopy = INDEXR;
int count = 0;
while (I >= Indexl && J >= Indexl + len + 1) {if (Nums[i] > Nums[j]) {//reverse order
copy[indexcopy--] = nums[i--]; Count = count + J-len-indexl;
}else{copy[indexcopy--] = nums[j--];
} while (I >= indexl) copy[indexcopy--] = nums[i--];
while (J >= Indexl + len + 1) copy[indexcopy--] = nums[j--];
for (int k=indexl; k<=indexr; k++) {nums[k] = copy[k];
} commonutils.printarray (copy);
Return Leftcount + count + rightcount; }
}
Test code:
public class _q36test extends TestCase {
_q36 inversepair = new _q36 ();
public void Test () {
int array[] = {7, 5, 6, 4};
System.out.println (Inversepair.inversepairs (array));
}