The sword refers to the offer surface Question 36: reverse order in the array and its deformation (Leetcode 315. Count of Smaller Numbers after self)

Source: Internet
Author: User

Sword Point 36: Reverse order in an array

title: in the array of two numbers, if the previous number is greater than the following number, then the two numbers constitute an inverse pair. Enter an array to find the total number of reverse pairs in this array.

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), output 5.


Submission URL: http://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tqId=11188

or http://ac.jobdu.com/problem.php?pid=1348


Input:
Each test case consists of two lines: the first row contains an integer n, which represents the number of elements in the array. where 1 <= n <= 10^5. The second row contains n integers, and each array is of type int.
Output:
For
each test case, output an integer that represents the total number of reverse pairs in the array.
Sample input:
4
7 5 6 4
Sample output:
5


Analysis:

The definition of (inversion Pairs) in reverse order:

A[i] < A[j] and i > J, then A[i] and A[j] is an inverse pair. The total number of reverse pairs is given a set of numbers, which requires the calculation of the number of reverse pairs in the sequence.


An example of an array of {7, 5, 6, 4} was analyzed to analyze the process of statistical reverse 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.



As shown in 5.1 (a) and Figure 5.1 (b), the array is decomposed into two sub-arrays of length 2, and the two sub-arrays are split into two sub-arrays of length 1 respectively. 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.



Reverse to Total Count=leftcount+rightcount+crosscount


Note: The last step of copying the last remaining 4 of the second subarray to the secondary array is omitted.  

(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.   adds 2 to the number of reverse order and copies 7 to the auxiliary array, moving forward P1 and P3.
(b) P1 points to the number P2 pointing to the number, there is no reverse order. Copy the number P2 points to the secondary array, and move forward P2 and p3. 
(c) P1 points to a number 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.   Adds 1 to the number of reverse order and copies 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 form a reverse pair (5.2 (b)). Each time we compare, we copy the larger numbers from the back 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 a detailed discussion, we can summarize the process of statistical reverse order: First, the array is separated into sub-arrays, the number of reverse pairs in the sub-array is counted first, and then the number of inverse pairs between the two adjacent sub-arrays is counted. In the process of counting reverse pairs, you also need to sort the arrays. If you are familiar with sorting algorithms, it is not difficult to find that this sort of process is actually a merge sort.


AC Code:

#include <cstdio> #include <vector>using namespace Std;class solution {Public:int Inversepairs (vector<        int> data) {int len = data.size ();                if (len==0) return 0;    return GetCount (data, 0, len-1);  }int GetCount (vector<int>& data, int begin, int end)//Here data needs to use & for reference value {if (Begin >= end) return         0;        recursive termination condition int mid = (begin + End)/2;   int lCount = GetCount (data, begin, mid);                 Recursion, merge sort, and calculate this inverse logarithm int rcount = getcount (data, mid+1, end); Vector<int> Temp=data;  Auxiliary array, used to merge sort int foridx=mid, backidx=end, tempidx=end;    FORIDX: Subscript for the first half, Backidx: subscript for the second half, tempidx: subscript int crosscount = 0 for the auxiliary array; Log the inverse logarithm of the intersection while (Foridx>=begin && backidx >= mid+1) {if (Data[foridx] > Data[b                ACKIDX])//There are cross reverse pairs, first count, and then put the larger values in the auxiliary array {temp[tempidx--] = data[foridx--]; Crosscount + = BackidX-mid;  } else {temp[tempidx--] = data[backidx--]; There is no cross-reversed pair, the larger value is placed in the secondary array}} while (Foridx >= begin) temp[tempidx--] = Data[foridx        --];        while (Backidx >= mid+1) temp[tempidx--] = data[backidx--];         for (int i=begin; i<=end; i++) data[i] = Temp[i];    return (Lcount+rcount+crosscount);    }};//below is the test part int main () {solution Sol;    Vector<int> vec1={8,4,2,7,6,2};    Vector<int> vec2={1,2,3,9,8,7,6};         Vector<int> vec3={7,5,6,4}; int Num1=sol.    Inversepairs (VEC1); int Num2=sol.    Inversepairs (VEC2); int Num3=sol.        Inversepairs (VEC3);     printf ("%d\n", NUM1);    printf ("%d\n", num2);                printf ("%d\n", num3); return 0;}



315. Count of Smaller Numbers after self

Total Accepted: 9951 Total submissions: 32512 Difficulty: Hard

Submission URL: https://leetcode.com/problems/count-of-smaller-numbers-after-self/

You were given an integer array nums and you had to return a new counts array. The counts array has the property where are the number of smaller elements to the right of counts[i] nums[i] .

Example:

Nums 2 1 1 0 smaller element.

Return the array [2, 1, 1, 0] .



RELATED links:

Count inversions in an array | Set 1 (Using Merge Sort)-Geeksforgeeks http://www.geeksforgeeks.org/counting-inversions/

Given An array of pairs, find all symmetric pairs in It-geeksforgeeks Http://www.geeksforgeeks.org/given-an-array-of-pai rs-find-all-symmetric-pairs-in-it/

Using inversion Pair -An elegent o (n) time complexity and O (1) space complexity Algorithm-leetcode discuss

https://leetcode.com/discuss/7319/an-elegent-time-complexity-and-space-complexity-algorithm?show=9834#a9834

The sword refers to the offer surface question 36-reverse order in the array-small site Noxus-Blog channel-Csdn.net http://blog.csdn.net/wtyvhreal/article/details/45664949



The sword refers to the offer surface Question 36: reverse order in the array and its deformation (Leetcode 315. Count of Smaller Numbers after self)

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.