Today's topic
👉 Python 문제 풀이
Python 문제 중 접근하기 어려운 문제에 대해 회고하기 위함으로 포스팅함
문제
숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.
예를 들어,
nums = [3,2,3]
return 3
nums = [2,2,1,1,1,2,2]
return 2
가정
`nums` 배열의 길이는 무조건 `2` 이상입니다.
1st 접근법
- count() 사용하여 수가 과반수로 접근
def more_than_half(nums):
for i in set(nums) :
if nums.count(i) > len(nums)/2 :
return i
2nd 접근법
- max()를 사용하여 majority로 접근
def more_than_half(nums):
nums_new = set(nums)
result = []
for i in nums_new:
result.append(nums.count(i))
for i in nums_new:
if nums.count(i) == max(result) :
return i
My opinion
- 문제를 어떻게 이해하느냐에 따르 문제 풀이 방법도 달라질 수 있다는 것을 깨달았다.