Leetcode_35. 搜索插入位置

定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。

你可以假設數組中無重複元素。

方法比較蠢,不喜勿噴。

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!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章