定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重複元素。
方法比較蠢,不喜勿噴。
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!