- Date : 2021.08.08(일)
- Time : 20분
- Given an array
nums of size n, return the majority element. - The majority element is the element that appears more than
⌊n / 2⌋times. You may assume that the majority element always exists in the array.
- n == nums.length
- 1 <= n <= 5 * 10^4
- -2^31 <= nums[i] <= 2^31 - 1
- Input: nums = [2,2,1,1,1,2,2]
- Output: 2
from collections import Counter
class Solution:
def majorityElement(self, nums: list[int]) -> int:
return (Counter(nums).most_common()[0][0]): 사실 이 문제는 가장 많은 요소가 무엇인지 찾는 문제이기 때문에 Counter클래스를 사용했다. collections 모듈의 Counter클래스는 데이터의 개수를 셀 때 유용하게 쓸 수 있다. 여기서는 데이터의 개수가 많은 순으로 정렬된 배열을 리턴하는 most_common이라는 메서드를 사용하였다. 제일 앞에 제일 많은 개수의 데이터가 오기 때문에 그 요소를 return 해주었다.