LeetCode/Top Interview 150

169. Majority Element

hyunkookim 2024. 11. 26. 14:31

169. Majority Element

 

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        res = {} # hashmap
        for n in nums:
            if n in res:
                res[n]+=1
            else:
                res[n] = 1
        # 다수 요소 찾기: 빈도 값 기준으로 최대값을 가진 키 반환
        return max(res, key=res.get)

 

 

 

Follow-up: Could you solve the problem in linear time and in O(1) space?

'LeetCode > Top Interview 150' 카테고리의 다른 글

121. Best Time to Buy and Sell Stock  (0) 2024.11.26
189. Rotate Array  (0) 2024.11.26
80. Remove Duplicates from Sorted Array II  (0) 2024.11.25
26. Remove Duplicates from Sorted Array  (0) 2024.11.25
27. Remove Element  (0) 2024.11.25