leetcode35. 搜索插入位置 🌟

题目:

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

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

示例 1:

  输入: [1,3,5,6], 5
  输出: 2
示例 2:

  输入: [1,3,5,6], 2
  输出: 1
示例 3:

  输入: [1,3,5,6], 7
  输出: 4
示例 4:

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

来源:力扣(LeetCode)
解答:

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        def binarySearch(nums, target):
            low = 0
            high = len(nums) - 1
            while low <= high:
                cur = int((low + high) / 2)
                if nums[cur] == target:
                    return cur, None
                elif nums[cur] > target:
                    high = cur - 1
                elif nums[cur] < target:
                    low = cur + 1
            return -1, low
        
        target, low = binarySearch(nums, target)
        return low if target == -1 else target
View Code

 

def binarySearch(nums, target, low, high):
    if low > high:
        return low
    cur = (low + high) // 2
    if nums[cur] == target:
        return cur
    elif nums[cur] > target:
        return binarySearch(nums, target, low, cur - 1)
    else:
        return binarySearch(nums, target, cur + 1, high)

return binarySearch(nums, target, 0, len(nums) - 1)
View Code

 

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        for i, num in enumerate(nums):
            if num >= target:
                return i
        
        return len(nums)
View Code

 

posted @ 2019-07-04 09:48  catyuang  阅读(175)  评论(0编辑  收藏  举报