搜索插入位置的解决之路= =
题目描述
测试案例(部分)
第一次
很简单,用列表的index
函数就可以实现了。
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
return nums.index(target)
测试,通过了。直接提交,发现报错。
原来是存在列表中不存在的target,所以我们加一个判断即可。
第二次
又看了下题目描述,说如果不存在target,就要返回target插入的位置,所以我们还需要多写一点,判断插入的位置。
因为输入的列表序列是有序的升序序列
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
for k, v in enumerate(nums):
if v > target:
return k
else:
continue
测试,通过。提交,又错了。
检查一下逻辑,有一种情况是target大于列表中的所有元素,所以函数最终返回的是null,那我们可以在最后补上一个return解决这个问题。
第三次
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
for k, v in enumerate(nums):
if v > target:
return k
else:
continue
return len(nums)
提交,通过。
因为题目比较简单,而且花费时间也就12ms,慢的话也就24ms,就算结束了。