LeetCode----Insert Position

Search Insert Position

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.

Here are few examples.
[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(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        left = 0
        right = len(nums) - 1
        while left <= right:
            mid = (left + right) / 2
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        return left


(ps:最近CSDN博客取消了发布首页功能了,俺想了一下这个博客以后估计没啥人会看了,遂打算将这个博客只当成一个线纪录网站了。)



你可能感兴趣的:(二分查找)