[LeetCode] 35. Search Insert Position_Easy tag: Binary Search

 

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

Example 2:

Input: [1,3,5,6], 2
Output: 1

Example 3:

Input: [1,3,5,6], 7
Output: 4

Example 4:

Input: [1,3,5,6], 0
Output: 0

Update: 04/13/2019, 添加第4种方式,个人认为是面试过程中最适合用的。

思路就是Binary Search, 找到first position s.t A[i] >= target

Code

1) 利用python的built-in function     bisect.bisect_left

class Solution:
    def searchInsert(self, nums, target):
        return bisect.bisect_left(nums, target)

 

2) 利用python的built-in function     bisect.bisect

class Solution:
    def searchInsert(self, nums, target):
       return nums.index(target) if target  in nums else bisect.bisect(nums, target)

 

3) basic 做法, first position s.t A[i] >= target

        if not nums: return 0
        l, r = 0, len(nums)-1
        while l + 1 < r:
            mid = l + (r - l)//2
            if nums[mid] < target:
                l = mid
            elif nums[mid] > target:
                r = mid
            else:
                return mid  # 因为没有duplicates
        if nums[l] >= target:
            return l
        elif nums[r] >= target:
            return r
        else:
            return r+1  # 因为有可能比最大的还大

 

4) 还是用binary search的模板,只不过要注意左右边界,尤其是左边界时,如果小于或者等于nums中的最小值,都要返回0;但是右边界如果大于是len(n),如何是相等则是len(n)- 1。

class Solution:
    def searchInsert(self, nums, target):
        l, r = 0, len(nums) - 1
        if not nums or nums[l] >= target:
            return 0
        if nums[r] < target:
            return len(nums)
        while l + 1 < r:
            mid = l + (r - l)//2
            if nums[mid] > target:
                r = mid
            elif nums[mid] < target:
                l = mid
            else:
                return mid
        return r     # 这里直接return r 是因为边界已经考虑,所以最起始的r要么是等于target,要么是> target, 而l 也以为边界已经考虑的原因,
所以最起始的l肯定是小于target的,所以不可能是l(另外if语句里只有在nums[mid] < target 才会改变l)所以一定是r。

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9552824.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值