Question
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.
Example 1:
Input: nums = [3,2,3]
Output: 3
Plain Text
복사
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Plain Text
복사
My Answer
class Solution:
def majorityElement(self, nums: List[int]) -> int:
dict = {}
for num in nums:
if num not in dict:
dict[num] = 1
else:
dict[num]+=1
return max(dict, key=dict.get)
Python
복사
count 수 다루는 문제는 웬만하면 다 dictionary로 풀리는거같다.
dict의 key 중에서 가장 value가 큰 값을 return 하려면 dict.get 사용
dict.get = key에 해당하는 value값 가져옴
Optimized Version
No Optimization Needed
Python
복사