ITeye博客

数组中出现次数超过一半的数字

hwy1782 · 2010-10-27 10:45 · 算法 · 编程语言 · Markdown

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

bool g_bInputInvalid = false;//输入的数组是否合法 

int MoreThanHalfNum(int * array ,unsigned int length){
    
    if(array == null && length <= 0){
             g_bInputInvalid = true;
             return 0;
         }
    
    g_bInputInvalid = false;
    
    int result = array[0];
    int times = 1;
    for(int i=1; i<length; i++){ 
          if(times == 0){
               result = array[i];
               times = 1;
               }
          }
          else if(result == array[i]){
               times ++
               } 
          else{
               times --
               }
    }

    //检测是否满足大于一半 
    times = 0;
    for(int i= 0;i<length;i++){
            if(result == array[i]){
                      times++;
                 }
          }
    if(times*2 < length){
            g_bInputInvalid = true;
            result = 0;   
         }
 
    return result;
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。