Leetcode(35)-- 搜索插入位置

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。

你可以假设数组中无重复元素。

输入: [1,3,5,6], 5
输出: 2
输入: [1,3,5,6], 2
输出: 1
输入: [1,3,5,6], 7
输出: 4
输入: [1,3,5,6], 0
输出: 0

方法的核心:二分法

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

感受: 这题实质就是在考察二分法的算法

猜你喜欢

转载自blog.csdn.net/qq_20412595/article/details/82731107