# LC 704, 35, 34, 69 367
## LC 704 Binary Search
Binary Search, two std ways of implementations:
[## 704. 二分查找](https://programmercarl.com/0704.%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE.html#_704-%E4%BA%8C%E5%88%86%E6%9F%A5%E6%89%BE)
```python
# 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
[35.搜索插入位置](https://programmercarl.com/0035.%E6%90%9C%E7%B4%A2%E6%8F%92%E5%85%A5%E4%BD%8D%E7%BD%AE.html#%E6%80%9D%E8%B7%AF)
## LC 34
[34. 在排序数组中查找元素的第一个和最后一个位置](https://programmercarl.com/0034.%E5%9C%A8%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%E4%B8%AD%E6%9F%A5%E6%89%BE%E5%85%83%E7%B4%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%92%8C%E6%9C%80%E5%90%8E%E4%B8%80%E4%B8%AA%E4%BD%8D%E7%BD%AE.html#%E6%80%9D%E8%B7%AF)
### 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 the `nums[]`, there is no need for the second binary search.
#### Using `bisect`
It serves more like a wrapper. Reference [here](https://docs.python.org/3/library/bisect.html).
``` python
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
[69. Sqrt(x)](https://leetcode.com/problems/sqrtx/)
### Logic
Analogue to the binary search.
`num[0-len(num)]`: `range(x)`
index 0: $0^2$
index -1: $x^2$, 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
[367. Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/)
### Logic
Analogue to LC 367.
**Break condition:** `mid * mid == num`