35. 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.

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

注意最后区间讨论,然后返回插入的位置

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

请多多指教。

文章标题:35. Search Insert Position

本文作者:顺强

发布时间:2020-03-01, 23:59:00

原始链接:http://shunqiang.ml/leetcode-35-search-insert-p/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏