문제/릿코드

[릿코드/LeetCode] 169. Majority Element (파이썬3/Python3)

개 살구 2021. 7. 18. 19:33

문제

https://leetcode.com/problems/majority-element/

 

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


생각

리스트를 set으로 한 번 감싸고 최대 개수를 가지는 친구 찾기!

이제 그 친구가 n/2 이상이면 ㄱㄱ


코드

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        n = set(nums)
        max_n = 0
        max_c = 0
        for i in n:
            c = nums.count(i)
            if max_c < c:
                max_c = c
                max_n = i
        if max_c >= len(nums)/2:
            return max_n
        else:
            return 0