KK's blog

每天积累多一些

0%

LeetCode 169 Majority Element

LeetCode



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 * 10<sup>4</sup>
-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1

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

题目大意:

求数组中的众数

解题思路:

编程之美的水王法

解题步骤:

N/A

注意事项:

  1. Python代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    def majorityElement(self, nums: List[int]) -> int:
    candidate, count = 0, 0
    for i in range(len(nums)):
    if count == 0:
    candidate = nums[i]
    count += 1
    continue
    if nums[i] == candidate:
    count += 1
    else:
    count -= 1
    return candidate

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview