定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
方法比较蠢,不喜勿喷。
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(len(nums)-1):
if target == nums[i]:
return i
for i in range(len(nums)-1, -1, -1):
if target > nums[i] :
return i+1
return 0
学习到了数组反向遍历,很多次提交错误,因为第二位写了0,其实应该是-1!