題目:數組中有一個數字出現的次數超過數組長度的一半,請找出整個數字。例如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 }
運行截圖:
固然還有一些方法,好比咱們能夠先將數組排序,那麼若是數組最中間的元素必定是該數組中超過數組
長度一半的元素。