剑指offer-面试题29.数组中出现次数超过一半的数字

题目:数组中有一个数字出现的次数超过数组长度的一半,请找出整个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在整个数组中出现5次,超过数组长度的一半,输出2.

 

此题的解法有很多种,剑指offer书中提出了两种,一种是Parition的方法,另外一种是计数的方法。

 

这里我们用计数的方法来实现一下。试想当我们遍历数组的时候用一个计数器。当遇到相同的数时计数器加1,遇到不同的数计数器减1,然而数组中有数字超过数组长度的一半,则肯定计数器最后的值是大于等于1,所以超过一半的数肯定是使计数器最后一次设为1的数字。

 

 

代码如下:

复制代码
 1 #include <iostream>
 2 using namespace std;
 3 
 4 int FindNumberMuchHalf(int array[],int length)
 5 {
 6     if(array==NULL||length<=0)
 7         return 0;
 8 
 9     int result=array[0];
10     int count=1;
11 
12     for(int i=1;i<length;i++)
13     {
14         if(count==0)
15         {
16             result=array[i];
17             count=1;
18         }
19         else if(result==array[i])
20         {
21             count++;
22         }
23         else
24         {
25             count--;
26         }
27     }
28 
29     return result;
30 }
31 
32 int main()
33 {
34     int array[]={1,2,3,2,2,2,5,4,2};
35     int len=9;
36     int ans;
37     ans=FindNumberMuchHalf(array,len);
38     cout<<"The Ans is "<<ans<<endl;
39     system("pause");
40     return 0;
41 }
复制代码

运行截图:

 

当然还有一些方法,比如我们可以先将数组排序,那么如果数组最中间的元素一定是该数组中超过数组长度一半的元素。

剑指offer-面试题29.数组中出现次数超过一半的数字_第1张图片

你可能感兴趣的:(剑指offer)