题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。
示例
输入: [1,3,5,6], 5
输出: 2
输入: [1,3,5,6], 2
输出: 1
输入: [1,3,5,6], 7
输出: 4
输入: [1,3,5,6], 0
输出: 0
解答
错误解答
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
i=0
while i<len(nums):
# i处值恰好等于目标值
if nums[i]==target:
return i
else:
# 列表遍历完,列表内的值都比target大,则将target插入列表末尾
if i==len(nums)-1:
nums.append(target)
return len(nums)-1
# target处于某两个值之间
elif nums[i]<=target and nums[i+1]>target:
nums.insert(i+1,target)
return i+1
i += 1
条件判断 elif nums[i]<=target and nums[i+1]>target 过于严格,没有考虑到nums[0]小于target的情况
正确解答
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(len(nums)):
if nums[i]>=target:
return i
# 列表遍历结束都没有返回,说明target不在nums中且比nums中的数都大
return len(nums)