관리 메뉴

솜씨좋은장씨

[leetCode] 169. Majority Element (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 169. Majority Element (Python)

솜씨좋은장씨 2020. 6. 23. 01:05
728x90
반응형

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

 

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

Solution

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        keys = set(nums)
        answer = 0
        
        for key in keys:
            if nums.count(key) > len(nums) / 2:
                answer = key
                break
        return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments