leetcode - 229. Majority Element II

Description

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

1 <= nums.length <= 5 * 10^4
-10^9 <= nums[i] <= 10^9

Solution

Boyer-Moore Majority Vote, find the first 2 majorities, then check if they appear more than n/3 times.

For boyer-moore majority vote, if we want to find multiple majorities, use new element to decrease all previous counters.

Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        n1, c1, n2, c2 = 0, 0, 1, 0
        for each_num in nums:
            if each_num == n1:
                c1 += 1
            elif each_num == n2:
                c2 += 1
            elif c1 == 0:
                n1, c1 = each_num, 1
            elif c2 == 0:
                n2, c2 = each_num, 1
            else:
                c1 -= 1
                c2 -= 1
        c1, c2 = 0, 0
        for each_num in nums:
            if each_num == n1:
                c1 += 1
            elif each_num == n2:
                c2 += 1
        res = []
        if c1 > len(nums) / 3:
            res.append(n1)
        if c2 > len(nums) / 3:
            res.append(n2)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值