跳转至

169.majority-element

Statement

Metadata
  • Link: 多数元素
  • Difficulty: Easy
  • Tag: 数组 哈希表 分治 计数 排序

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

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

 

示例 1:

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

示例 2:

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

 

进阶:

  • 尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。

Metadata
  • Link: Majority Element
  • Difficulty: Easy
  • Tag: Array Hash Table Divide and Conquer Counting Sorting

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?

Solution

from typing import List


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

最后更新: October 11, 2023
回到页面顶部