給定一個排序數(shù)組和一個目標值,在數(shù)組中找到目標值,并返回其索引。如果目標值不存在于數(shù)組中,返回它將會被按順序插入的位置。
你可以假設(shè)數(shù)組中無重復(fù)元素。
示例 1:
輸入: [1,3,5,6], 5
輸出: 2
示例 2:
輸入: [1,3,5,6], 2
輸出: 1
示例 3:
輸入: [1,3,5,6], 7
輸出: 4
示例 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
for i in range(len(nums)):
if target == nums[i]:
return i
if target < nums[i]:
nums.insert(i, target)
return i
nums.insert(i+1, target)
return i+1
思路:主要利用了list對象的insert方法。循環(huán)列表,找到就返回,如果發(fā)現(xiàn)有小于的,且程序沒有返回,說明元素不存在,即插入,然后返回索引。注意當循環(huán)結(jié)果后都沒有返回的情況。