숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.
예를 들어,
nums = [3,2,3]
return 3
nums = [2,2,1,1,1,2,2]
return 2
nums
배열의 길이는 무조건 2
이상입니다.
일단 문제를 보고 set으로 중복을 제거한 다음 어떻게 해볼까도 생각했지만,
간편하게 dictionary에 담아서 sort를 하기로 했다.
def more_than_half(nums):
dict = {}
for i in nums:
if not dict.get(i):
dict[i] = 1
else:
dict[i] += 1
new_list = sorted(dict.items(), key=lambda x: x[1], reverse=True)
return new_list[0][0]
print(more_than_half([3,2,3]))