binary search
https://blog.csdn.net/itsyarkee/article/details/6852338
http://www.cnblogs.com/grandyang/p/6854825.html
https://leetcode.com/problems/minimize-max-distance-to-gas-station/description/
https://www.jianshu.com/p/de025ad0d6b5
- consider inital boundary, exit case (<, <=, diff<1e-6), and int v.s. float
- Standard Version (go through all elements of the list if not found)12345678910l, r = 0, len(nums)-1while l<=r:m = l + (l - r)/2if nums[m] > target:r = m - 1elif nums[m] < target:l = m + 1else:return mreturn "Not Found"
https://github.com/Frees0u1/ClassicalCode/blob/master/301_BinarySearch.cpp
find the first satisfied index (lower bound)
12345678910# lower小于, upper小等# 找到nums[l, r)大于等于key值的第一个元素位置 [左闭-右开)l, r = 0, len(nums)while l < r:m = l + (r - l)/2if nums[m] < target:l = m + 1else: # nums[m] >= targetr = mreturn l if nums[l] == target else Nonefind the first satisfied index that greater than target (upper bound 1)
12345678910# lower小于, upper小等# 找到严格大于key值的第一个元素l, r = 0, len(nums)while l < r:m = l + (r - l)/2if nums[m] <= target:l = m + 1else:r = mreturn l if l < len(nums) and nums[l] > target else Nonefind the last satisfied index (upper bound 2)
12345678910# lower小于, upper小等# 找到严格大于key值的第一个元素l, r = 0, len(nums)while l < r:m = l + (r - l)/2if nums[m] <= target:l = m + 1else:r = mreturn l-1 if 0<=l-1 < len(nums) and nums[l-1] == target else None
or12345678l, r = 0, len(nums)-1while l < r: m = l + (r - l)/2 if nums[m] <= target: l = m else: r = m - 1 return l
- float binary search12345678l, r = min(A), max(A)while r - l > 0.00001:m = (r+l) /2.0if possible(m):l = melse:r = mreturn l
2D binary search
- n m matrix convert to an array => matrix[x][y] => a[x m + y]
- an array convert to n * m matrix => a[x] =>matrix[x / m][x % m];
Binary Modifications
- acceleration123456789# https://leetcode.com/problems/divide-two-integers/description/while dividend >= divisor:i, tmp = 1, divisorwhile dividend >= divisor:dividend -= divisorres += idivisor <<= 1i <<= 1divisor = tmp
Intervals
- sort by (start, -end)
- find and merge, use binary search to accelerate
https://www.hrwhisper.me/leetcode-intervals/
Interval Fundamentals
|
|
Meeting rooms
|
|