LeetCode17.10(2021.7.9)

LC面试题 17.10. 主要元素

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = -1, count = 0;
        for (int num : nums) {
            if (!count) candidate = num;
            if (num == candidate) count++;
            else count--;
        }
        count = 0;
        int length = nums.size();
        for (int num : nums)
            if (num == candidate) count++;
        return count * 2 > length ? candidate : -1;
    }
};

发表评论