这道题实际上不难,用很笨的方法也是能解答出来的,但是浪费了程序的时间和空间,从网上查到一种思路,觉得不错。

        有个数字出现的次数超过了数组长度的一半,也就是,有个数字出现的次数比其他所有数字出现次数的和还要多。遍历数组时保存连个值,一个是数组中的数字,一个是出现的次数,遍历到一个数字时,如果该数字和之前保存的数字相同,则次数加一,如果该数字和之前保存的数字不同,则次数减一,如果次数为零,遍历下一个数组元素,并把次数设为一。要找的数字肯定是最后一次把次数设为1时对应的数字。

 

  1. #include   <iostream>  
  2. using   namespace   std;  
  3. bool g_bInputInvalid = false;  
  4. int MoreThanHalfNum(int* numbers, unsigned int length)  
  5. {  
  6.     if(numbers == NULL && length == 0)  
  7.     {  
  8.         g_bInputInvalid = true;  
  9.         return 0;  
  10.     }  
  11.     g_bInputInvalid = false;  
  12.     int result = numbers[0];  
  13.     int times = 1;  
  14.     for(int i = 1; i < length; ++i)  
  15.     {  
  16.         if(times == 0)  
  17.         {   result = numbers[i];  
  18.             times = 1;  
  19.         }  
  20.         else if(numbers[i] == result)  
  21.             times++;  
  22.         else 
  23.             times--;  
  24.     }  
  25.     // verify whether the input is valid  
  26.     times = 0;  
  27.     forint i = 0; i < length; ++i)  
  28.     {  
  29.         if(numbers[i] == result)  
  30.             times++;  
  31.     }  
  32.     if(times * 2 <= length)  
  33.     {  
  34.         g_bInputInvalid = true;  
  35.         result = 0;  
  36.     }  
  37.     return result;  
  38. }  
  39. void main()  
  40. {  
  41.     int a[]={1,2,2,3,4,5,2,2,2};  
  42.     int re=MoreThanHalfNum(a,9);  
  43.     cout<<re;  
  44. }