高级农民
- 积分
- 1686
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-7-11
- 最后登录
- 1970-1-1
|
8.8 打卡三道binary search。index细节太多还需要学习
#34. Find first and last position of element in sorted array
run binary search twice to find lower bound and upper bound
idx1 = helper(nums, target)
idx2 = helper(nums, target + 1) - 1
if idx1 < len(nums) and nums[idx1] == target:
return [idx1, idx2]
else:
return [-1, -1]
The tip for this method is that if target is not in the array, for example in this case, [5,7,7,8,8,10] with target 6 will give us index [1, 0], but since nums[idx1] != target it will output [-1, -1]
Another tricky way:
double left = target - 0.5, right = target + 0.5;
int l = bs(nums, left), r = bs(nums, right);
if(l == r) return new int[]{-1, -1};
return new int[]{l, r-1};
#33. Search in rotated sorted array
Determine whether mid point is on the left side of the pivot or the right side. Plot the array as a 分段函数。
if nums[low] <= nums[mid]: binary search left
else: binary search right
#81. Search in rotated sorted array II
Mid is a floor of (l+r)/2, so it can be equal to l. We want to make sure that the equal sign in condition nums[i] <= nums[mid] only happens when l = mid, so you have to remove the duplicates for the left. ex: [3,3,3,3,3,3,4,5,3]
However for the right, it's not necessary, and it can make the calculation slower. For example find 2 in [0, 1, 2, 3, 3, 3, 3, 3, 3, 3], all the 3s can be skipped in a O(logN) manner if you don't do the r -=1, if you do, it will be O(N)
和上面一题同样的分段,但是多了一个dedup的条件:
while l < mid and nums[l] == nums[mid]: # tricky part
l += 1
|
|