반응형
난이도 - Easy
Intuition
1) Hash Map
class Solution:
def majorityElement(self, nums: List[int]) -> int:
hash_map = defaultdict(int)
max_freq = 0
ans = 0
for num in nums:
hash_map[num] += 1
if hash_map[num] > max_freq:
max_freq = hash_map[num]
ans = num
return ans
Time Complexity: O(n)
Space Complexity: O(n)
2) Boyer-Moore Voting Algorithm
class Solution:
def majorityElement(self, nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += 1 if num == candidate else -1
return candidate
Time Complexity: O(n)
Space Complexity: O(1)
반응형
'코딩 알고리즘 문제 > Leetcode' 카테고리의 다른 글
| Finding Pairs With a Certain Sum (Array, Hash Table, Design) (0) | 2025.10.25 |
|---|---|
| 26. Remove Duplicates from Sorted Array (0) | 2025.10.25 |
| 695. Max Area of Island (Array, Depth-First Search, Breadth-First Search, Union Find, Matrix) (0) | 2025.10.24 |
| 1047. Remove All Adjacent Duplicates In String (0) | 2025.10.24 |
| 986. Interval List Intersections (Array, Two Pointers, Line Sweep) (0) | 2025.10.24 |