-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer_51
50 lines (41 loc) · 1005 Bytes
/
offer_51
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//面试题51:数组中的逆序对
int InverPair(int* data,int length)
{
if(data==nullptr || length==0)
return 0;
int* copy=new int[length];
for(int i=0;i<length;++i)
copy[i]=data[i];
int count=InversePairsCore(data,copy,0,length-1);
delete[] copy;
return count;
}
int InversePairsCore(int *data,int* copy,int start,int end)
{
if(start==end){
copy[start]=data[start];
return 0;
}
int length=(end-start)/2;
int left=InverPairCore(copy,data,start,start+length);
int right=InverPairCore(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 left+right+count;
}