1. 程式人生 > >Leetcode 35.搜尋插入位置(Python3)

Leetcode 35.搜尋插入位置(Python3)

35.搜尋插入位置

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

你可以假設陣列中無重複元素。

示例 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

 

自己的程式碼:

思想:還是二分查詢

#search-insert-position
class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        low = 0
        high = len(nums) - 1
        while low <= high:
            mid = (low + high) // 2
            guess = nums[mid]
            if guess == target:
                return mid
            if guess < target:
                low = mid + 1
            else:
                high = mid - 1
        return low

 

發現大神也是二分法,如果是用for來遍歷那麼時間複雜度O(n),while的話,就可以實現二分法,時間複雜度可以達到O(logn)

 

連結:

https://leetcode-cn.com/problems/search-insert-position/