[leetcode] 169. Majority Element

题目

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

Constraints:

  • n == nums.length
  • 1 <= n <= 5 * 104
  • -109 <= nums[i] <= 109

Follow-up: Could you solve the problem in linear time and in O(1) space?

思路

  1. 用字典存储列表元素出现的频率,随后获取出现频率最高的元素。
  2. 遍历列表,与此同时维护maxNum、cnt分别表示出现频率最高的元素与频率。当遍历到相同元素时,cnt加一,否则cnt减一。如果cnt为零,则更换maxNum为当前元素。

代码

python版本:

from collections import Counter
from typing import List, Optional
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        cnt = Counter(nums)
        return cnt.most_common(1)[0][0]

    
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        maxNum, cnt = 0, 0
        for num in nums:
            if cnt:
                cnt = cnt+1 if num == maxNum else cnt-1
            else:
                cnt = 1
                maxNum = num
        return maxNum

posted @ 2022-06-01 22:02  frankming  阅读(16)  评论(0编辑  收藏  举报