給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。 你可以假設數組中無重覆元素。 示例 1: 輸入: [1,3,5,6], 5 輸出: 2 示例 2: 輸入: [1,3,5,6], 2 輸出: 1 示例 3: 輸入: [1,3,5 ...
給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重覆元素。
示例 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: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ index=-1 last=0 try: return nums.index(target) except: for i in range(len(nums)): if target > nums[i]: last+=1 nums.insert(last,target) return index if index > 1 else last