面试题36 数组中的逆序对

题目描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
 1 class Solution {
 2 public:
 3     int InversePairsCore(vector<int> &data,vector<int>&copy,int start,int end)
 4     {
 5         if(start==end)
 6         {
 7             copy[start]=data[start];
 8             return 0;
 9         }
10         int length = (end-start)/2;
11         int left = InversePairsCore(copy,data,start,start+length);
12         int right = InversePairsCore(copy,data,start+length+1,end);
13           
14         int i = start + length;
15         int j = end;
16         int indexCopy = end;
17         int count=0;
18         while(i>=start&&j>=start+length+1)
19         {
20             if(data[i]>data[j])
21             {
22                 copy[indexCopy--]=data[i--];
23                 count+=j-start-length;
24             }
25             
26             else
27             {
28                 copy[indexCopy--]=data[j--];
29             }
30         }
31         for(;i>=start;--i)
32             copy[indexCopy--] = data[i];
33         for(;j>=start+length+1;--j)
34             copy[indexCopy--] = data[j];
35         return left+right+count;
36         }
37     int InversePairs(vector<int> data) {
38         int length = data.size();
39         if(length<=0)
40             return 0;
41         vector<int> copy;
42         for(int i=0;i<length;i++)
43             copy.push_back(data[i]);
44         int count = InversePairsCore(data,copy,0,length-1);
45         copy.clear();
46         return count;
47     }
48      
49      
50 };
原文地址:https://www.cnblogs.com/wanderingzj/p/5358600.html