LeetCode Search Insert Position

来源:互联网 发布:国税 软件开发 编辑:程序博客网 时间:2024/06/07 04:01

LeetCode解题之Search Insert Position


原题

在一个有序数组中,如果目标数字存在,则返回它的下标,否则返回它应该插入位置的下标值。

注意点:

  • 数组中没有重复数字

例子:

输入: nums = [1, 3, 5, 6], target = 5
输出: 2

输入: nums = [1, 3, 5, 6], target = 2
输出: 1

解题思路

又是一道二分搜索的题。分以下几种情况:如果当前数字是目标数字,或者当前数字大于目标数字而它之前的数字小于目标数字,则返回当前下标;如果当前数字为最后一个且它比目标数字小,则返回当前下标的后一位。

AC源码

class Solution(object):    def searchInsert(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: int        """        length = len(nums)        start = 0        end = length        while start < end:            mid = (start + end) // 2            if nums[mid] == target or (nums[mid] > target                 and (mid == 0 or nums[mid - 1] < target)):                return mid            if mid == length - 1 and nums[mid] < target:                return mid + 1            if nums[mid] < target:                start = mid + 1            else:                end = midif __name__ == "__main__":    assert Solution().searchInsert([1, 3, 5, 6], 5) == 2    assert Solution().searchInsert([1, 3, 5, 6], 2) == 1    assert Solution().searchInsert([1, 3, 5, 6], 7) == 4    assert Solution().searchInsert([1, 3, 5, 6], 0) == 0

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

0 0