LC 704, 35, 34, 69 367
LC 704 Binary Search
Binary Search, two std ways of implementations:
## 704. 二分查找
# lc 704
def search(self, nums: List[int], target: int) -> int:
low = 0
high = len(nums)
while low < high:
mid = low + (high - low) // 2
if nums[mid] < target:
low = mid + 1
elif nums[mid] > target:
high = mid
else:
return mid
return -1
Logic
- In this case, the initial condition is set to [low, high).
- high: strict upper bound, which gives
low < high
. - When updating, [low, high) condition hold.
LC 35
LC 34
Logic:
- Two binary search, one for the lower bound, another for the upper bound.
- edge cases:
len(nums) == 0
- if the first binary search results in the case where the
target
is not within the range of thenums[]
, there is no need for the second binary search.
Using bisect
It serves more like a wrapper. Reference here.
import bisect
def searchRange2(self, nums: List[int], target: int) -> List[int]:
start = bisect.bisect_left(nums, target)
if start == len(nums) or nums[start] != target:
return [-1, -1]
return [start, bisect.bisect_right(nums, target, lo=start) - 1]
LC 69
Logic
Analogue to the binary search.
num[0-len(num)]
: range(x)
index 0:
0
2
0^2
02
index -1:
x
2
x^2
x2, yeah I know there is a better bound by doing some math, but no thanks.
Break condition: target == nums[mid]
: mid * mid <= x < (mid + 1) * (mid + 1)
LC 367
Logic
Analogue to LC 367.
Break condition: mid * mid == num