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.
给定一个排序数组和一个目标值,如果找到目标,返回索引。如果没有,返回按顺序插入的索引所在的位置。
您可以假定数组中没有重复项。
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
直接遍历
class Solution:
def searchInsert(self, nums, target):
if len(nums)<0:
return 0
for i in range(0,len(nums)):
if nums[i]>=target:
return i
return i+1
if __name__=='__main__':
a=[1,3,5,6]
b=7
c=Solution().searchInsert(a,b)
print(c)