求解超过数组中半数的元素(Majority Element)

类似消消乐游戏,每次取一部分元素匹配,剩下的没有匹配的,即为超过半数元素的值

class Solution {
    public:
        int majorityElement(vector<int>& nums) {
        size_t length = nums.size();
        int tag = nums[0];
        int i = 0;
        int count = 1;

        while (i+1<length) {
            if (tag!=nums[i+1]) {
                count--;
            } else {
                count++;
            }
            if (count==0&&(i+2)<length) {
                tag = nums[i+2];
                i+=2;
                count = 1;
            } else {
                i++;
            }
        }
        return tag;
    }
};
发布了264 篇原创文章 · 获赞 272 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105349382