【leetcode】169. 多数元素

多数元素

    • 题目
    • 题解
      • 1. 哈希表
      • 2. 摩尔投票

题目

169. 多数元素

给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

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

示例 2:

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

题解

1. 哈希表

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        dict = {}
        n = len(nums)
        for num in nums:
            if num not in dict:
                dict[num] = 1
            else:
                dict[num] += 1

        max_key = 0
        max_value = 0
        for key, value in dict.items():
            if value > max_value:
                max_key = key
                max_value = value
        return max_key

            

        

2. 摩尔投票

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        # 摩尔投票
        votes = 0
        for num in nums:
            if votes == 0:
                x = num
            if num == x:
                votes += 1
            else:
                votes -= 1
        return x

            

        

你可能感兴趣的:(LeetCode,leetcode,算法,职场和发展)