鱼C论坛

 找回密码
 立即注册
查看: 3158|回复: 0

[学习笔记] Leetcode 229. Majority Element II

[复制链接]
发表于 2020-9-23 03:15:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]
Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

  1. class Solution:
  2.     def majorityElement(self, nums: List[int]) -> List[int]:
  3.         num1, num2, c1, c2 = 0, 0, 0, 0
  4.         
  5.         for num in nums:
  6.             if num == num1:
  7.                 c1 += 1
  8.             elif num == num2:
  9.                 c2 += 1
  10.             elif c1 == 0:
  11.                 num1 = num
  12.                 c1 = 1
  13.             elif c2 == 0:
  14.                 num2 = num
  15.                 c2 = 1
  16.             else:
  17.                 c1 -= 1
  18.                 c2 -= 1
  19.         
  20.         
  21.         c1 = c2 = 0
  22.         
  23.         for num in nums:
  24.             if num == num1:
  25.                 c1 += 1
  26.             elif num == num2:
  27.                 c2 += 1
  28.         
  29.         result = []
  30.         length = len(nums) // 3
  31.         
  32.         if c1 > length:
  33.             result.append(num1)
  34.         if c2 > length:
  35.             result.append(num2)
  36.         return result
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 04:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表