Sword refers to the offer question (Java version): The reverse order in the array to __ sword refers to offer (Java version)

Source: Internet
Author: User

Title: Two digits in an array if the previous number is greater than the following number, then these two numbers form a reverse-order pair. Enter an array to find out the total number of reverse pairs in this array

For example, in the array {7,5,6,4}, there are altogether 5 pairs of reverse pairs, respectively {7,6},{7,5},{7,4},{6,4},{5,4}.

When we see this topic, our first reaction is to scan the entire array sequentially. Each time you scan an array, compare the number to the size of the number that follows it. If the following number is smaller than it is, then these two digits form a reverse-order pair. Suppose the array contains n numbers. Because each number is compared to the O (n) number, the time complexity of the algorithm is O (N2). We're trying to find a faster algorithm.

We take the array {7,5,6,4} as an example to analyze the process of statistical reverse alignment, each time we scan a number, we can not compare it with each of the following numbers, otherwise the time complexity is O (N2) So we can consider the first comparison of two adjacent numbers.

As shown in the following figure, we first decompose the array into two 2-length sub arrays, and then divide the two sub arrays into two subgroups of 1 of the length of the tea city. The next side merges adjacent sub arrays, while counting the number of reverse pairs. In the first pair of 1-length sub-array {7},{5}, 7 is greater than 5, so {7,5} consists of a reverse-order pair. Also in the second pair of sub array {6},{4} with length 1 has a reverse order to {6,4}. Since we have counted the internal inverse pairs of these two arrays, we need to sort these pairs so that we do not repeat the statistics in the future statistical process.


Next we count the inverse pairs of the two-length 2-array of substrings.

We first point to the end of the two sub arrays with two pointers, and compare the numbers pointing to the two pointers at a time. If the number in the first child array is greater than the number in the second child array, it constitutes a reverse alignment and the number of reverse pairs equals the number of remaining digits in the second child array. 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 order pair. Each time we compare, we copy the larger numbers from the back to a secondary array, ensuring that the numbers in the secondary array are sorted incrementally. After copying the larger number to the array, move the corresponding pointer one bit forward, and then proceed to the next round of comparisons.

After a detailed discussion, we suspect that we have summed up the process of statistical reverse alignment: First, the array is separated into a child array, the number of inverse pairs in the sub array is first counted, and then the number of reverse pairs between the two adjacent sub arrays is counted. In the process of statistical reverse alignment, you also need to sort the array. If you are familiar with the sorting algorithm, it is not difficult to find that this sort of process is a merge sort.

Implementing the above procedure with Java code

/** * Reverse Order: * Two digits in an array if the preceding number is greater than the following number, then these two digits form a reverse-pair.
 * Enter an array to find out the total number of reverse pairs in this array.

* * Package swordforoffer;

Import java.util.ArrayList; /** * @author Jinshuangqi * * * August 9, 2015 * * public class E36inversepairs {private arraylist<integer> Assignli
		St (arraylist<integer> list, int start,int end) {arraylist<integer> des = new arraylist<integer> ();
		for (int i = start;i<end;i++) {Des.add (List.get (i));
	} return des;
		Public long mergetwolist (arraylist<integer> list,int start,int half,int end) {Long Count = 0;
		arraylist<integer> templeft = assignlist (list,start,half);
		arraylist<integer> tempright = assignlist (list,half,end);
		int leftindex = 0;
		int rightindex = 0;
		int index = start;
			while (Leftindex < Templeft.size () && rightindex <tempright.size ()) {int temp1 = Templeft.get (Leftindex);
			int temp2 = Tempright.get (Rightindex);
				if (Temp1 > Temp2) {count+=templeft.size ()-Leftindex; List. Set (index, TEMP2);
				index++;
			rightindex++;
				}else{list.set (index, TEMP1);
				index++;
			leftindex++;
			for (; Leftindex < Templeft.size (); leftindex++) {list.set (index, Templeft.get (Leftindex));
		index++;
			for (; Rightindex <tempright.size (); rightindex++) {list.set (index, Tempright.get (Rightindex));
		index++;
	return count;
		Public long getinversions (arraylist<integer> list,int start,int end) {Long Count = 0;
		if ((End-start) <= 1) return 0;
		int half = start+ (End-start)/2;
		Count + = Getinversions (list,start,half);
		Count + = Getinversions (list,half,end);
		Count + = Mergetwolist (list,start,half,end);
	return count;
		Public long Getinversepairs (int[] arr) {arraylist<integer> Al = new Arraylist<integer> ();
		for (int i = 0;i<arr.length;i++) {al.add (arr[i]);
		int end =arr.length;
	Return getinversions (Al,0,end);
		public static void Main (string[] args) {int[] arr={7,5,6,4}; E36inversepairs Test = new E36inversepairs ();
	System.out.println (Test.getinversepairs (arr));
 }
}


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.