[python algorithm]

HYEYOON·2021년 2월 2일
0

문제

숫자로 이루어진 배열인 nums를 인자로 전달합니다.

숫자중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.

예를 들어,

nums = [3,2,3]
return 3

nums = [2,2,1,1,1,2,2]
return 2

가정

nums 배열의 길이는 무조건 2개 이상


solution1.

def more_than_half(nums):

  # a = {}
  # for i in nums:
  #   if i not in a:
  #     a[i] = 1
  #   else:
  #     a[i] += 1

  # max_num = max(a.values())

  # for i in a.keys():
  #   if a[i] == max_num:
  #     return i

solution2.

def more_than_half(nums):
  for i in range(len(nums)):
    check[nums[i]] += 1
  return check.index(max(check)) if max(check) > len(nums) // 2 else 0

solution3.

def more_than_half(nums):
  for num in nums:
    if nums.count(num) > len(nums) // 2:    #len(nums)//2를 하는 이유는 과반수
      return num

3번 진짜 짧다.. 대박스...알고리즘 화이팅..

profile
Back-End Developer🌱

0개의 댓글

관련 채용 정보