https://leetcode.com/problems/search-insert-position/
思路就是 BS,只要最后记得return low就行
参考http://www.cnblogs.com/zuoyuan/p/3772705.html
my code:
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0; high = len(nums) - 1
while low <= high:
mid = (low + high)/2
if nums[mid] > target:
high = mid - 1
elif nums[mid] < target:
low = mid + 1
else:
return mid
return low # 这里只要return low 就可以了。自己分情况讨论
其实可以简化
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0; high = len(nums) - 1
while low <= high:
mid = (low + high)/2
if nums[mid] >= target:#这里加上等号
high = mid - 1
else:
low = mid + 1
return low # 这里只要return low 就可以了。自己分情况讨论
这里不要返回high,会有错误。