Reverse Order pairs in the array "offoffer" and reverse order in" offoffer"
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5? Rp = 2 & ru =/ta/coding-interviews & qru =/ta/coding-interviews/question-ranking
Description
Two numbers in the array. If the first number is greater than the subsequent number, the two numbers form a reverse order. Enter an array to find the total number of reverse pairs in this array.
Ideas
We can make full use of the characteristics of the merge sort to calculate the reverse logarithm of the array. First, we divide the entire array. During the merge process, we have ensured that when merging, the left and right subarrays must be ordered, so we start from the end of the two self-arrays, and choose the big one each time. If the big one is in the left array, then, the reverse order will increase the number of elements in the right sub-array of the merged array.
Then, divide the entire merging process into subproblems and use recursion to solve them.
class Solution{public:int InversePairs(vector<int> data){int len = data.size();if(len==0)return 0;int count = Megre(data,0,len-1);return count;}int Megre(vector<int> &data,int start,int end){if(start==end)return 0;int mid = (end+start)/2;int left = Megre(data,start,mid);int right = Megre(data,mid+1,end);int len = data.size();vector<int> copy(len);for(int k = 0; k<len; k++)copy[k] = data[k];int i = mid;int j = end;int index = end;int count = 0;while(i>=start && j>=mid+1){if(copy[i]>copy[j]){data[index--] = copy[i--];count += j-mid;}else{data[index--] = copy[j--];}}for(; i>=start; --i)data[index--] = copy[i];for(; j>=mid+1; --j)data[index--] = copy[j];return (left+right+count);}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source