Created
May 4, 2017 05:08
-
-
Save Hanaasagi/2872fc7b6dd9fbd2c42f31b614be34ef to your computer and use it in GitHub Desktop.
可以找出元素第一次出现位置的二分查找
This file contains hidden or 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 binary_search(l, t): | |
low, high = -1, len(l) | |
while low+1 != high: | |
mid = (low + high) / 2 | |
if l[mid] < t: | |
low = mid | |
else: | |
high = mid | |
pos = high | |
if pos >= len(l) or l[pos] != t: | |
pos = -1 | |
return pos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment