언어/Python
TIL39 | CodeKata 가장 자주 등장한 숫자 출력하기, 물을 담을 수 있는 가장 넓은 면적
lee365
2021. 10. 29. 13:23
반응형
CodeKata Week 2
문제 4
숫자로 이루어진 배열인 nums를 인자로 전달합니다.
숫자 중에서 과반수(majority, more than a half)가 넘은 숫자를 반환해주세요.
def more_than_half(nums):
# 구현
input
nums = [3,2,3]
nums = [2,2,1,1,1,2,2]
output
3
2
나의 풀이
각 요소별 count 비교
def top_k(nums, k):
set_list = set(nums)
result = [(target, nums.count(target)) for target in set_list]
result.sort(key = lambda x : -x[1])
return [result[i][0] for i in range(k)]
문제 5
인자인 height는 숫자로 이루어진 배열입니다.그래프로 생각한다면 y축의 값이고, 높이 값을 갖고 있습니다.
아래의 그래프라면 height 배열은 [1, 8, 6, 2, 5, 4, 8, 3, 7] 입니다.
https://storage.googleapis.com/replit/images/1555380144403_97221ca23fbb92beaae5b6c800ceb5c8.pn
저 그래프에 물을 담는다고 생각하고, 물을 담을 수 있는 가장 넓은 면적의 값을 반환해주세요.
def get_max_area(height):
# 구현
input
height = [1,8,6,2,5,4,8,3,7]
output
49
나의 풀이
def get_max_area(height):
area = 0
for start in range(len(height)):
for end in range(len(height)-1, start, -1):
min_height = min(height[start], height[end])
area = max(min_height * (end-start), area)
return area
- 브루트 포스 알고리즘으로 가장 최선의 값을 찾는 문제라고 생각해 완전 탐색하는 방식으로 구현했다.
반응형