继续把知乎发的挪到这里https://zhuanlan.zhihu.com/p/38404527
题目:
Given a sorted array and a target value, return the index if the
target is found. If not, return the index where it would be if it were
inserted in order.
You may assume no duplicates in the array.
Examples :
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
思路:基于假设列表已排序且无重复值可以利用条件判断来插入位置。
Solution:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for idx, val in enumerate(nums):
diff = target-val
# same value with target
if diff == 0:
return idx
# biger than target
elif diff < 0:
return idx
return len(nums)