【面试题29】数组中出现次数超过一半的数字

【题目描述】

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

【解决方案】

解法一:基于Partition函数的O(n)算法

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

 1         public static int MoreThanHalfNum(int[] arr)
 2         {
 3             if (arr == null || arr.Length < 1)
 4                 return 0;
 5 
 6             int mid = arr.Length >> 1;
 7             int start = 0;
 8             int end = arr.Length - 1;
 9 
10             int index = Partition(arr, start, end);
11 
12             while (index != mid)
13             {
14                 if (index > mid)
15                     index = Partition(arr, start, index - 1);
16                 else
17                     index = Partition(arr, index + 1, end);
18             }
19 
20             return arr[mid];
21         }
22 
23         public static int Partition(int[] arr, int start, int end)
24         {
25             int key = arr[start];
26 
27             while (start < end)
28             {
29                 while (start < end && arr[end] >= key)
30                     end--;
31                 arr[start] = arr[end];
32 
33                 while (start < end && arr[start] <= key)
34                     start++;
35                 arr[end] = arr[start];
36             }
37 
38             arr[start] = key;
39 
40             return start;
41         }

解法二:根据数组特点找出O(n)的算法

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

 1         public static int MoreThanHalfNum(int[] arr)
 2         {
 3             if (arr == null || arr.Length < 1)
 4                 return -1;
 5 
 6             int result = arr[0];
 7             int times = 1;
 8 
 9             for (int i = 1; i < arr.Length; i++)
10             {
11                 if (times == 0)
12                 {
13                     result = arr[i];
14                     times = 1;
15                 }
16                 else if (arr[i] == result)
17                     times++;
18                 else
19                     times--;
20             }
21 
22             return result;
23         }

 

posted @ 2015-09-14 16:20  叫我霍啊啊啊  阅读(188)  评论(0编辑  收藏  举报