1150번과 매우 유사한 문제다. 다만 다른 점은 해당 문제에선 Majority Element가 반드시 있다는 가정하에 이를 반환하는 것이고, 1150은 input으로 주어진 숫자가 Majority Element가 맞는지 틀린지를 반환하는 것이다.
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
class Solution:
def majorityElement(self, nums: List[int]) -> int:
dic = defaultdict(int)
l = len(nums) // 2
for i, n in enumerate(nums):
dic[n] += 1
if dic[n] > l:
return n
참고:
'기술(Tech, IT) > 리트코드(LeetCode)' 카테고리의 다른 글
[LeetCode] 392. Is Subsequence (0) | 2023.07.14 |
---|---|
[LeetCode] 229. Majority Element II (0) | 2023.07.13 |
[LeetCode] 70. Climbing Stairs (0) | 2023.07.11 |
[LeetCode] 1150. Check If a Number Is Majority Element in a Sorted Array (0) | 2023.07.10 |
[LeetCode] 1057. Campus Bikes (0) | 2023.06.15 |