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

 

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.empty())return 0;
     int time=0,num=0;
      for(int i=0;i<numbers.size();i++)
          {
          if(i==0)
              {
              num=numbers[i];
              time++;
          }
          else 
              {
              if(time==0)
                  num=numbers[i];
              if(num==numbers[i])
                  time++;
              else             
                  time--; 
              
          }
      }
        time=0;
       for(int i=0;i<numbers.size();i++)
           {
           if(num==numbers[i])
             time++;
       }
        if(time*2<=numbers.size())
            return 0;
        else 
            return num;
    }
};

 

posted on 2016-04-11 09:15  RenewDo  阅读(117)  评论(0编辑  收藏  举报

导航