Binary Search html
T(n) = T(n/2) + O(1) => T(n) = O(lg n)oop
proof:url
若是能用iterable , 就用while loop, 能夠防止用recursion的時候stack overflow( process in Linux is 8Mb), stack room is static for each process. (堆空間, heap room 是內存, 是動態的。)層數越多,存儲更多中間/臨時變量,最終超過系統配的stack空間,就會出現stack overflow。spa
建議:.net
- 若是問題不復雜,能用iterable就用iterablecode
- 若是問題比較複雜,仍是用recursive吧htm
1) ask 是否有duplicates?blog
1.1 若是沒有duplicates內存
標準的binary search:get
a) l + 1 < r 至關於若是l, r 相鄰就跳出,這樣可以避免死循環. 可是while loop以後須要加一個判斷, 也就是d選項
b) l + (r - l)//2 # 不用(l+r)//2 , 由於l + r 有可能overflow,強行裝*,當l + r 之和超過int的最大值,2的32次方減1,會溢出。
c) A[mid] ==, <, > # 爲了bug free, 建議舉個小栗子, 而後畫圖去判斷.
d) A[l], A[r] ? target
Code
def BinarySearch(self, nums, target): # nums is sorted if not nums or target < nums[0] or target > nums[-1]: return -1 l, r = 0, len(nums) -1 # note here is len(nums) -1 while l + 1 < r: mid = l + (r - l)//2 if nums[mid] > target: r = mid elif nums[mid] < target: l = mid else: return mid if nums[l] == target: return l if nums[r] == target: return r return -1
1.2 若是有duplicates
a) ask 是first index, last index or dont matter?
若是是first index:
if A[mid] == target: r = mid
最後判斷 A[l] 和A[r] 的時候先判斷 A[l]
若是是last index:
if A[mid] == target: l = mid
最後判斷 A[l] 和A[r] 的時候先判斷 A[r]
Questions:
[LeetCode] 704. Binary Search_Easy tag: Binary Search
[LeetCode] 374. Guess Number Higher or Lower_Easy tag: Binary Search
[LeetCode] 34. Find First and Last Position of Element in Sorted Array == [LintCode] 61. Search for a Range_Easy tag: Binary Search first index and last index == target in duplicates.
[LeetCode] 35. Search Insert Position_Easy tag: Binary Search first index >= target, without duplicates
[LeetCode] 278. First Bad Version_Easy tag: Binary Search first index, without duplicates
[LeetCode] 162. Find Peak Element(852. Peak Index in a Mountain Array)_Medium tag: Binary Search
[LeetCode] 74. Search a 2D Matrix_Medium tag: Binary Search
[LeetCode] 240. Search a 2D Matrix II_Medium tag: Binary Search
[LeetCode] 69. Sqrt(x)_Easy tag: Binary Search
[LeetCode] 153. Find Minimum in Rotated Sorted Array_Medium tag: Binary Search first index <= nums[-1]
[LeetCode] 154. Find Minimum in Rotated Sorted Array II_Hard tag: not real binary search anymore
[LeetCode] 33. Search in Rotated Sorted Array_Medium tag: Binary Search
[LeetCode] 81. Search in Rotated Sorted Array II_Medium tag: not real binary search anymore
[LeetCode] 702. Search in a Sorted Array of Unknown Size_Medium tag: Binary Search
[LeetCode] 4. Median of Two Sorted Arrays_Hard tag: Array, Binary Search