고양이발일기
[Python] HackerRank - Closest Numbers 본문
반응형
Problem
Solving Process
주어진 배열을 Sort 하고,
for 문을 돌면서 diff 값을 비교하여 minimum 값을 찾으며
새로운 min 값이면 redefine,
같은 min 값이면 add 해주는 식으로 진행하였다!
Solution
def closestNumbers(arr):
arr.sort()
length = len(arr)
min = sys.maxsize
ans_arr = []
for i in range(length):
if i != length-1:
diff = arr[i+1] - arr[i]
if min > diff:
min = diff
ans_arr = [arr[i], arr[i+1]]
elif min == diff:
ans_arr.append(arr[i])
ans_arr.append(arr[i+1])
return ans_arr
반응형
'알고리즘' 카테고리의 다른 글
[Python] HackerRank - Tower Breakers (0) | 2023.05.15 |
---|---|
[Python] LeetCode - Is Subsequence (1) | 2023.05.12 |
[Python] LeetCode - Isomorphic Strings (0) | 2023.05.11 |
[Python] HackerRank - Seperate The Numbers (0) | 2023.05.11 |
[Python] 백준 10815 숫자카드 (1) | 2023.03.23 |
Comments