LeetCode 35 搜尋插入位置
阿新 • • 發佈:2021-02-09
難度簡單815收藏分享切換為英文接收動態反饋
給定一個排序陣列和一個目標值,在陣列中找到目標值,並返回其索引。如果目標值不存在於陣列中,返回它將會被按順序插入的位置。
你可以假設陣列中無重複元素。
示例 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 """ if not nums: return 0 if target in nums: return nums.index(target) min_index = 0 max_index = len(nums) - 1 while min_index <= max_index: middle_index = (min_index + max_index) / 2 if target < nums[middle_index]: max_index = middle_index - 1 else: min_index = middle_index + 1 return min_index