binary search는 동일하게, 같은 숫자가 나온 시점에서(예를 들어, 30이 있는 배열에서 30을 삽입하고 싶을때) 왼쪽으로 갈지(start == mid), 오른쪽으로 갈지(mid + 1 == end)의 차이
1. bisect_right
def climbingLeaderboard(ranked, player):
# Write your code here
def bisect_right(arr, value, start, end):
if start >= end:
return start
mid = start + (end - start) // 2
if value < arr[mid]:
return bisect_right(arr, value, start, mid)
else:
return bisect_right(arr, value, mid + 1, end)
ranked = sorted(list(set(ranked)))
ranks = []
len_ = len(ranked)
for score in player:
rank = len_ - bisect_right(ranked, score, 0, len_) + 1
ranks.append(rank)
return ranks
arr = [10, 20, 30, 40, 40, 50, 60, 70] 일때,
# mid, 선택된 arr
4 [10, 20, 30, 40, 40, 50, 60, 70]
6 [50, 60, 70]
5 [50]
5
2. bisect_left
def bisect_left(arr, value, start, end):
if start >= end:
return start
mid = start + (end - start) // 2
if arr[mid] < value:
return bisect_left(arr, value, mid + 1, end)
else:
return bisect_left(arr, value, start, mid)
arr은 동일,
# mid, 선택된 arr
4 [10, 20, 30, 40, 40, 50, 60, 70]
2 [10, 20, 30, 40]
3 [40]
3
'# 코딩 문제 관련 > 파이썬' 카테고리의 다른 글
[HackerRank-python] Designer PDF Viewer (0) | 2022.07.19 |
---|---|
[HackerRank-python] The Hurdle Race (0) | 2022.07.14 |
[HackerRank-python] Picking Numbers (0) | 2022.07.11 |
[HackerRank-python] Forming a Magic Square (0) | 2022.07.10 |
[HackerRank-python] Cats and a Mouse (0) | 2022.07.10 |