1. 程式人生 > 其它 >[leetcode] 169. Majority Element

[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