leetcode题解

【Leetcode】35—Search Insert Posit

2019-07-21  本文已影响0人  Gaoyt__
一、题目描述

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。
示例:

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

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

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

输入: [1,3,5,6], 0
输出: 0
二、代码实现
方法一、利用python中自带的index,但引入了sort,导致速度很慢
class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            return nums.index(target)
        else:
            nums.append(target)
            nums.sort()
            return nums.index(target)
方法二、二分查找

在普通的二分查找基础上,插入一个判断,当查找到最后一个数字时,如果查找到数字就返回当前索引,如果查找不到当前数字则判断一下和最后查找的数字的大小,返回相应的位置。

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        def BinarySearch(nums, target):
            low = 0
            high = len(nums) - 1
            while low <= high:
                mid = (low + high)/2
                if nums[mid] == target: return mid
                elif nums[mid] > target: high = mid - 1
                else: low = mid + 1
                    
            if nums[mid] < target: return mid + 1
            else: return mid
                               
        return BinarySearch(nums, target)
上一篇下一篇

猜你喜欢

热点阅读