题目:数组中有一个数字出现的次数超过数组长度的一半,请找出整个数字。例如ios
输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。因为数字2在整个数组中出现5次,数组
超过数组长度的一半,输出2.spa
此题的解法有不少种,剑指offer书中提出了两种,一种是Parition的方法,另外code
一种是计数的方法。blog
这里咱们用计数的方法来实现一下。试想当咱们遍历数组的时候用一个计数器。排序
当遇到相同的数时计数器加1,遇到不一样的数计数器减1,然而数组中有数字超过数it
组长度的一半,则确定计数器最后的值是大于等于1,因此超过一半的数确定是使io
计数器最后一次设为1的数字。class
代码以下:
stream
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 }
运行截图:
固然还有一些方法,好比咱们能够先将数组排序,那么若是数组最中间的元素必定是该数组中超过数组
长度一半的元素。