[leetcode] 169. Majority Element

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;
    }
};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容