-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.py
68 lines (60 loc) · 1.82 KB
/
BinarySearch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 查找第一个值等于给定值的元素
def find1(source, target):
low, high = 0, len(source)-1
while low <= high:
mid = low + (high - low) // 2
if source[mid] == target:
if mid == 0 or source[mid - 1] != target:
return mid
else:
high = mid - 1
elif source[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# 查找最后一个值等于给定值的元素
def find2(source, target):
low, high = 0, len(source)-1
while low <= high:
mid = (high - low) // 2 + low
if source[mid] < target:
low = mid + 1
elif source[mid] > target:
high = mid - 1
else:
if mid == len(source) - 1 or source[mid + 1] != target:
return mid
else:
low = mid + 1
return -1
# 查找第一个大于等于给定值的元素
def find3(source, target):
low, high = 0, len(source)-1
while low <= high:
mid = (high - low) // 2 + low
if source[mid] >= target:
if mid == 0 or source[mid - 1] < mid:
return mid
else:
high = mid - 1
else:
low = mid + 1
return -1
# 查找最后一个小于等于给定值的元素
def find4(source, target):
low, high = 0, len(source)-1
while low <= high:
mid = (high - low) // 2 + low
if source[mid] <= target:
if mid == len(source) - 1 or source[mid + 1] > target:
return mid
else:
low = mid + 1
else:
high = mid-1
return -1
print(find1([1, 3, 4, 5, 6, 8, 8, 8, 11, 18], 8))
print(find2([1, 3, 8, 8, 8, 11, 18], 8))
print(find3([3, 4, 6, 7, 10], 2))
print(find4([3, 4, 6, 8, 9, 10], 2))