美文网首页
数组中数字出现次数超过一半的数字。

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

作者: shuixingge | 来源:发表于2016-04-29 10:33 被阅读131次

思路:

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
           if(array==null||array.length==0)
                       return 0;
           if(array.length==1)
                       return array[0];
           int count=1;
           int  res=array[0];
           for(int i=1;i<array.length;i++){
                     if(array[i]==res)
                           count++;
                     else 
                           count--;
                     if(count==0){
                         count=1;
                         res=array[i];
                    }
           }
           int len=0;
           if(int i=0;i<array.length;i++){
                  if(array[i]==res)
                        len++;
           }
            if(len*2>array.length)
                   return res;
   }

相关文章

网友评论

      本文标题:数组中数字出现次数超过一半的数字。

      本文链接:https://www.haomeiwen.com/subject/ugwhrttx.html