"Sword refers to offer study" "Face question 36: reverse order in array"

Source: Internet
Author: User

title: Two numbers in an array 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. Example Analysis

For example in the array {7, 5, 6, 4, there are altogether 5 reverse pairs, respectively (7, 6), (7,5), (7, 4), (6, 4), and (5, 4).

Problem Solving Ideas:

The first type: direct solution

Sequentially scans the entire array. Each time a number is scanned, the size of the number and the number behind it is compared. If the subsequent number is smaller than it, then these two numbers make up an inverse pair. Suppose the array contains n digits. Since each number is compared to an O (n) number, the time complexity of the algorithm is O (n^2).

The second type: Analytical method

We use the array {7, 5, 6, 4} as an example to analyze the process of statistical inverse pairs. Each time we scan to a number, we can't compare it with every number in the back, otherwise the time complexity is O (n^5), so we can consider comparing two adjacent numbers first.

5. 1 (a) and Figure 5.1 (b), we first decomposed the array into two sub-arrays of length 2, and then split the two sub-arrays into two sub-arrays of length 1. The next side merges adjacent sub-arrays, counting the number of reverse pairs. In the first pair of sub-arrays of length 1 {7}, {5} 7 is greater than 5, so (7, 5) consists of an inverse pair. Also there are reverse pairs (6, 4) in the second pair of sub-arrays of length 1 {6}, {4}. Since we have already counted the inverse pairs inside the pairs array, we need to sort the two pairs (shown in Figure 5.1 (c)) to avoid repeating the statistics in the subsequent statistical process.

The last step in the note is omitted, which is to copy the last remaining 4 of the second sub-array into the secondary array.
(a) The number pointed to by P1 is greater than the number pointed to by P2, indicating that there is an inverse pair in the array. The number that P2 points to is the second number of the second Subarray, so the second sub-array has two digits smaller than 7. Add 2 to the number of reverse order, and copy 7 to the auxiliary array, moving forward P1 and P3.
(b) P1 points to the number P2 pointing to the number, no reverse order. Copy the number that P2 points to the secondary array and move forward P2 and P3.
(c) The number pointed to by P1 is greater than the number pointed to by P2, so there is an inverse pair. Since the number pointed to by P2 is the first number of the second subarray, only one digit in the sub-array is smaller than 5. Add 1 to the number of reverse order, and copy 5 to the auxiliary array, moving forward P1 and P3.

Next we count the inverse pairs between two sub-arrays of length 2. In Figure 5.2, we subdivide the combined sub-arrays of Figure 5.1 (d) and the process of statistical inverse pairs.
We first point to the end of two sub-arrays with two pointers, and compare the numbers pointed to by two pointers at a time. If the number in the first subarray is greater than the number in the second sub-array, the inverse pair is formed, and the number of reverse pairs is equal to the number of digits remaining in the second Subarray (5.2 (a) and Figure 5.2 (c)). If the number in the first array is less than or equal to the number in the second array, it does not constitute a reverse pair (5.2 (b)). Each time we compare, we copy the larger numbers from the forward to the secondary array, making sure the numbers in the auxiliary array are ascending. After the larger number is copied to the secondary array, move the corresponding pointer forward one bit, then the next round comparison.
After the detailed theory of poetics, we can summarize the process of statistical reverse order: first divide the array into sub-arrays, first count the number of reverse pairs within the subarray, and then count the number of reverse pairs between the two adjacent sub-arrays. In the process of counting reverse pairs, you also need to sort the arrays. If we are familiar with the sorting, it is not difficult to find that this sort of process is actually a merge sort.

Code implementation:
 Public classTEST36 { Public Static int Inversepairs(int[] data) {if(Data = =NULL|| Data.length <1) {Throw NewIllegalArgumentException ("Array Arg should contain at least a value"); }int[] copy =New int[Data.length]; System.arraycopy (data,0, copy,0, data.length);returnInversepairscore (data, copy,0, Data.length-1); }Private Static int Inversepairscore(int[] Data,int[] Copy,intStartintEnd) {if(start = = end) {Copy[start] = Data[start];return 0; }intLength = (end-start)/2;intleft = Inversepairscore (copy, data, start, start + length);intright = Inversepairscore (copy, data, start + length +1, end);Subscript for the last digit of the first half        inti = start + length;Subscript for last digit in//second half        intj = END;//Where to start copying        intIndexcopy = end;//Reverse number        intCount =0; while(I >= start && J >= start + length +1) {if(Data[i] > Data[j])                {Copy[indexcopy] = Data[i];                indexcopy--;                i--; Count + = J-(start + length);//corresponding reverse number}Else{Copy[indexcopy] = data[j];                indexcopy--;            j--; }        } for(; I >= start; i--)            {Copy[indexcopy] = Data[i];            indexcopy--;        i--; } for(; J >= start + length +1;            j--) {Copy[indexcopy] = data[j];            indexcopy--;        j--; }returnCount + left + right; } Public Static void Main(string[] args) {int[] data = {1,2,3,4,7,6,5}; System. out. println (Inversepairs (data));//3        int[] Data2 = {6,5,4,3,2,1}; System. out. println (Inversepairs (data2));//        int[] Data3 = {1,2,3,4,5,6}; System. out. println (Inversepairs (data3));//0        int[] data4 = {1}; System. out. println (Inversepairs (DATA4));//0        int[] Data5 = {1,2}; System. out. println (Inversepairs (DATA5));//0        int[] Data6 = {2,1}; System. out. println (Inversepairs (DATA6));//1        int[] Data7 = {1,2,1,2,1}; System. out. println (Inversepairs (DATA7));//3}}
Run Results

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Sword refers to offer study" "Face question 36: reverse order in array"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.