LeetCode Notes_#35 Search Insert Position

LeetCode Notes_#35 Search Insert Position

Contents

题目

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

思路和解答

思路

  • 题目要求
    给出一个顺序的数组和一个数字,然后在这个数组里寻找这个数字

    • 如果有这个数字,那么直接返回数字的索引
    • 如果没有这个数字,那么返回这个数字‘应该’的索引(按顺序排应该排在第几位?)
  • 思路

    • 无论有还是没有,应该满足一个规律:
      • 设指定数字为x,前后两个数字为a,b,那么一定有a≤x≤b
      • 而且从前往后的话遍历的话,一定是先遇到小的,然后才到大的,所以就是找第一个满足>x的数字,返回他的索引(相当于顶替它的位置);或者找到=x的数字,直接返回索引;找不到比他大的,那么就是索引是数组长度;找不到比他小的,那么返回0

解答

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if nums[0]>target:
            return 0
        if nums[-1]<target:
            return len(nums)
        for i in range(len(nums)):
            if nums[i]==target:
                return i
            elif nums[i]>target and i!=0:
                return i

20ms,faster than 99.96%

高票答案

高票答案都是用的二分法,相当于复杂度降低到了O(logn),但是使用二分法就需要去处理一些关于索引的问题,因为索引只能是整数,然而折半查找的时候总是会存在大了1号或者小了1号的情况

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

要注意的点

  • target是最大值或者最小值的情况要考虑到,并且单独处理
原文地址:https://www.cnblogs.com/Howfars/p/9839093.html