35 Search Insert Position
二分查找, 注意r指针指向的一直都是符合条件的最右边界
Python
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums)
while l < r:
mid = l + (r - l)/2
if nums[mid] < target:
l = mid + 1
else:
r = mid
return r
Java
class Solution {
public int searchInsert(int[] nums, int target) {
int left = 0;
int right = nums.length;
while(left < right){
int mid = left + (right - left) / 2;
if (nums[mid] < target)
left = mid + 1;
else
right = mid;
}
return right;
}
}