LeetCode算法题169:求众数解析

给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例1:

输入: [3,2,3]
输出: 3

示例2:

输入: [2,2,1,1,1,2,2]
输出: 2

这个题可以直接设置一个哈希表字典去计数每一个值出现的次数然后取次数最多的数,但是试过之后发现超过空间限制,说明还是限制了空间复杂度。因此上网搜索后发现一种方法叫摩尔投票法,这种方法就是因为题目给出一定存在一个数其个数是大于n/2的,所以设置一个投票计数器,选定第一个值作为起始值,然后后面的值如果是这个值那么计数加一,如果不等,那么计数减一,当计数器的值为零时,选取当前值作为新值继续计数。这样最后计数器不为零对应的值一定是出现次数大于一半的值。
C++源代码:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int result = 0;
        int count = 0;
        for (int i:nums)
        {
            if (result == i) count++;
            else if(count!=0) count--;
            else
            {
                result = i;
                count = 1;
            }
        }
        return result;
    }
};

python3源代码:

class Solution:
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = 0
        count = 0
        for i in nums:
            if count == 0:
                result = i
                count = 1
            elif result == i:
                count += 1
            else:
                count -= 1
        return result

猜你喜欢

转载自blog.csdn.net/x603560617/article/details/83903678