From f5be8aff86c19c0db2ad436897f9c95fb945aa0a Mon Sep 17 00:00:00 2001 From: xqm32 <458173774@qq.com> Date: Sun, 17 Sep 2023 11:02:33 +0800 Subject: [PATCH] leetcode: finished #229 --- content/leetcode/2023/9.md | 54 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/content/leetcode/2023/9.md b/content/leetcode/2023/9.md index e3a1c1b2f..cd3b0e7cc 100644 --- a/content/leetcode/2023/9.md +++ b/content/leetcode/2023/9.md @@ -3,6 +3,60 @@ title: 2023.9 draft: false --- +# 2023.9.17 + +```python +# +# @lc app=leetcode.cn id=229 lang=python3 +# +# [229] 多数元素 II +# + +# @lc code=start +from typing import List + + +class Solution: + def majorityElement(self, nums: List[int]) -> List[int]: + cand1, cand2 = 0, 0 + count1, count2 = 0, 0 + + for num in nums: + if num == cand1: + count1 += 1 + continue + if num == cand2: + count2 += 1 + continue + if count1 == 0: + cand1 = num + count1 += 1 + continue + if count2 == 0: + cand2 = num + count2 += 1 + continue + count1 -= 1 + count2 -= 1 + + count1, count2 = 0, 0 + for num in nums: + if num == cand1: + count1 += 1 + elif num == cand2: + count2 += 1 + + res = [] + if count1 > len(nums) // 3: + res.append(cand1) + if count2 > len(nums) // 3: + res.append(cand2) + return res + + +# @lc code=end +``` + # 2023.9.16 ```python