Reverse order in an array-sword point offer

Source: Internet
Author: User

The inverse of the array describes the topic

In the array of two digits, 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.

Ideas
    1. If the entire array is scanned, each number is larger than the number that follows, and the overall complexity is O (n^2)
    2. Can use the idea of the algorithm of merging sorting, at the same time to determine the order of the two sub-sequences in reverse, are from the back to the front row, if the previous number is greater than the number behind, because it is already in the order of the previous number is larger than the number of the following, reverse order for the remainder of the number of elements, and , then this element does not produce reverse order, normal ordering. Time complexity is O (NLOGN)
Code
PublicClass Solution {PublicIntInversepairs(int []Array) {if (Array = = NULL | |Array.Length = =0) {Return0; }int[] Copy =Newint[Array.Length];for (int i =0; I <Array.Length; i++) {Copy[i] =Array[i]; }int count = Inversecore (Array, copy,0,Array.Length-1);return count; }PublicIntInversecore(int[] Data,int[] Copy,int start,int end) {if (start = = end) {Copy[start] = Data[start];Return0; }int length = (end-start)/2;int left = Inversecore (copy, data, start, start + length);int right = Inversecore (copy, data, start + length + 1, end); int i = start + length; int j = end; int indexcopy = end; int count = 0; while (i >= start && J >= start + length + 1) {if (Data[i] > Data[j]) {copy[indexcopy--] = data[i--]; count + = J-(start + length);} else {copy[indexcopy--] = data[j--];}} for (; I >= start; i--) {copy[indexcopy--] = data[i];} for (; J >= Start+length+1; j--) {copy[indexcopy--] = data[j];} return count + left + right;}}         

Reverse order in array--sword point offer

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.