169. Majority Element
· 약 1분
[Majority Element - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com](https://leetcode.com/problems/majority-element/)
1. 해시맵 스타일(Dict, Counter 사용)
from collections import Counter
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counter = Counter()
for num in nums:
counter[num] += 1
return counter.most_common(1)[0][0]

2. 정렬 후 중앙값 반환
class Solution:
def majorityElement(self, nums: List[int]) -> int:
return sorted(nums)[len(nums) // 2]

3. Boyer-Moore Voting Algorithm
class Solution:
def majorityElement(self, nums: List[int]) -> int:
target, count = 0, 0
for num in nums:
if count == 0:
target = num
count += 1 if num == target else -1
return target

굉장히 유익한 문제였다.