Created
September 10, 2020 14:33
-
-
Save jsrimr/79762842555d3c8b0c9d56413d8a2116 to your computer and use it in GitHub Desktop.
binary serach 2가지 유형. Exact match and close match. close match 가 필요한 경우 : https://programmers.co.kr/learn/courses/30/lessons/64062
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_closest(): | |
""" | |
max_consecutive_cnt == k 인 경우가 여러개 있을 수 있다. 이 중 stone 을 가장 작게 하는 경우를 찾는다. | |
일단, max_consecutive_cnt >= k 를 만족하긴 해야한다. 여기를 =mid 로 잡고 | |
나머지 한쪽을 mid-1 이나 mid+1 해서 실험하는 용도로 사용한다. | |
left 는 항상 k에 못미달하는 구간으로(실패) 업데이트시 max_consecutive_cnt < k 일때 left = mid+1 | |
right 는 항상 k에 도달하는 구간으로(실패) max_consecutive_cnt >= k 에서 업데이트시 right = mid | |
""" | |
left = 0 | |
right = len(sorted_stones) - 1 | |
while left < right: # 등호가 없는게 특징이다 | |
mid = (left + right) // 2 | |
value = sorted_stones[mid] | |
max_consecutive_cnt = 0 | |
consecutive_cnt = 0 | |
for stone in stones: | |
if stone <= value: | |
consecutive_cnt += 1 | |
max_consecutive_cnt = max(max_consecutive_cnt, consecutive_cnt) | |
else: | |
consecutive_cnt = 0 | |
if max_consecutive_cnt >= k: | |
right = mid | |
else: | |
left = mid + 1 | |
def exact_match(): | |
""" | |
consecutive_cnt 가 k가 되는 경우가 한 경우밖에 없다면 이 방식의 bin_search 를 활용한다 | |
""" | |
while left <= right: # equal 이 있어야 함 | |
mid = (left + right) // 2 | |
value = sorted_stones[mid] | |
max_consecutive_cnt = 0 | |
consecutive_cnt = 0 | |
for stone in stones: | |
if stone <= value: | |
consecutive_cnt += 1 | |
max_consecutive_cnt = max(max_consecutive_cnt, consecutive_cnt) | |
else: | |
consecutive_cnt = 0 | |
if max_consecutive_cnt >= k: | |
right = mid -1 | |
elif max_consecutive_cnt == k: | |
break | |
else: | |
left = mid + 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment