Leetcode 169 Majority Element 分治

在一个长度为n的数组中找出出现次数超过(n+1)/2次的数

说明请参考编程之美中的2.3

class Solution {
public:
       int majorityElement(vector<int>& nums) {
        int candidate;
        int ntimes,i;
        for(ntimes = i = 0; i < nums.size(); ++i){
            if(ntimes == 0){
                candidate = nums[i],ntimes = 1;
            }
            else{
                if(candidate == nums[i]) ntimes ++;
                else ntimes--;
            }
        }
        return candidate;
    }
};

 

posted @ 2016-01-16 21:05  Breeze0806  阅读(334)  评论(0编辑  收藏  举报