📍문제
숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.
nums | return |
---|---|
[3,2,3] | 3 |
[2,2,1,1,1,2,2] | 2 |
<가정>
nums 배열의 길이는 무조건 2 이상입니다.
def more_than_half(nums):
a={}
for i in nums:
if i not in a: #딕셔너리 a 안에 i가 없으면
a[i] = 1 #해당 value = 1
else:
a[i]=a[i]+1 #없으면 value+1
return max(a, key=a.get) #value가 가장 큰 key값 찾기
def more_than_half(nums):
dict1 = {}
#b = []
for i in set(nums):
dict1.setdefault(i, nums.count(i))
return max(dict1, key=dict1.get)
def more_than_half(nums):
b = []
for i in set(nums):
if nums.count(i) > len(nums)/2:
b.append(i)
return b[0]