美文网首页
[leetcode] 169. Majority Element

[leetcode] 169. Majority Element

作者: 叶孤陈 | 来源:发表于2017-07-24 14:14 被阅读0次

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

分析:
本题让我们寻找超过出现n/2的数,可以采用多数投票算法,具体代码如下:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int num = nums.size();
        int major, count = 0;
        for(int i = 0; i < num; ++i)
        {
            if(count == 0) major = nums[i]; 
            if(nums[i] == major)
                count++;
            else
                count--;
            if(count > num/2) return major;
        }
        return major;
    }
};

相关文章

网友评论

      本文标题:[leetcode] 169. Majority Element

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