从有序数组中查找不小于(不大于)某数的第一个(最后一个)元素
Swift Lv6

记录一下二分查找的变形场景:

不小于某数的第一个元素

1
2
3
4
5
6
7
8
9
10
11
12
def binary_search_notlessthan_first(arr, target):
low = 0
high = len(arr)-1
res = -1
while low <= high:
mid = (low+high)//2
if target <= arr[mid]:
res = mid
high = mid-1
else:
low = mid+1
return res

如果 res==-1 ,说明 any(arr) < target


不大于某数的最后一个元素

1
2
3
4
5
6
7
8
9
10
11
12
def binary_search_notgreaterthan_last(arr, target):
low = 0
high = len(arr)-1
res = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] <= target:
res = mid
low = mid + 1
else:
high = mid - 1
return res

如果 res==-1 ,说明 any(arr) > target

Powered by Hexo & Theme Keep
Unique Visitor Page View