【面试题36】数组中的逆序对

【题目描述】

在数组中的两个数字如果前面一个数字大于后面的一个数字,则这两个数字组成一个逆序对。

输入一个数组,求出这个数组的逆序对的总数。

【解决方案】

 基于归并思想的解决方案。

我的代码实现,仅供参考:

 1         public static int InversePairs(int[] data)
 2         {
 3             if (data == null || data.Length <= 0)
 4             {
 5                 return 0;
 6             }
 7 
 8             int[] copy = new int[data.Length];
 9 
10             for (int i = 0; i < data.Length; i++)
11                 copy[i] = data[i];
12 
13             int count = InversePairsCore(data, copy, 0, data.Length - 1);
14 
15             return count;
16         }
17 
18         public static int InversePairsCore(int[] data, int[] copy, int start, int end)
19         {
20             if (start == end)
21             {
22                 copy[start] = data[start];
23                 return 0;
24             }
25 
26             int length = (end - start) / 2;
27 
28             int left = InversePairsCore(copy, data, start, start + length);
29             int right = InversePairsCore(copy, data, start + length + 1, end);
30 
31             //i初始化为前半段最后一个数字的下标
32             int i = start + length;
33             //j初始化为后半段最后一个数字的下标
34             int j = end;
35 
36             int indexCopy = end;
37             int count = 0;
38 
39             while (i >= start && j >= start + length + 1)
40             {
41                 if (data[i] > data[j])
42                 {
43                     copy[indexCopy--] = data[i--];
44                     count += j - start - length;
45                 }
46                 else
47                 {
48                     copy[indexCopy--] = data[j--];
49                 }
50             }
51 
52             for (; i >= start; i--)
53             {
54                 copy[indexCopy--] = data[i];
55             }
56 
57             for (; j >= start + length + 1; j--)
58             {
59                 copy[indexCopy--] = data[j];
60             }
61 
62             return left + right + count;
63         }

 

posted @ 2015-09-21 15:51  叫我霍啊啊啊  阅读(189)  评论(0编辑  收藏  举报