leetcode之majority number

来源:互联网 发布:基督教网络诗歌116首全 编辑:程序博客网 时间:2024/05/08 12:40

题目:

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.

解答:

典型的摩尔投票,由题意可知,最多还有一个主元素,直接进行摩尔投票即可

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

0 0
原创粉丝点击