zoukankan      html  css  js  c++  java
  • LeetCode 35. 搜索插入位置

    35. 搜索插入位置

    Difficulty: 简单

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

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

    示例 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
    

    Solution

    Language: 全部题目

    这是一道很简单很简单的数组题目,然而提交了三次才通过,只能说自己考虑问题太不全面了

    解法一(很脏):

    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            if not nums: return 0
            
            for i in range(len(nums)-1):
                if target > nums[i] and target <= nums[i+1]:
                    return i+1
                if target <= nums[i]:
                    return i
            return len(nums) if target > nums[-1] else 0
    

    解法二:

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

    下面是两次的错误提交记录:

    错误解法一:如果测试用例为

    [1]
    0
    

    测试不通过,数组的长度为零,此时for循环已经不起作用了,之间返回数组的长度,当target小于数组中唯一的元素时才能保持正确。

    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            if not nums: return 0
            
            for i in range(len(nums)-1):
                if target > nums[i] and target <= nums[i+1]:
                    return i+1
                if target < nums[i]:
                    return i
            return len(nums)
    

    错误解法二:由于粗心导致,for循环中除了target > nums[i]还有target <= nums[i]而不是target < nums[i],所以导致

    [1,3,5]
    1
    

    测试用例无法通过。

    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            if not nums: return 0
            
            for i in range(len(nums)-1):
                if target > nums[i] and target <= nums[i+1]:
                    return i+1
                if target < nums[i]:
                    return i
            return len(nums) if target > nums[-1] else 0
    
  • 相关阅读:
    Linux2.6X内核中文件相关结构体总结
    Linux 内核文件系统与设备操作流程分析
    在linux下删除的共享文件怎么恢复
    fedora17的U盘安装和硬盘安装
    cakephp
    【25.00%】【vijos P1907】飞扬的小鸟
    【14.36%】【codeforces 614C】Peter and Snow Blower
    【14.67%】【codeforces 615D】Multipliers
    【records】10.24..10.30
    【非常高%】【codeforces 733A】Grasshopper And the String
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14008388.html
Copyright © 2011-2022 走看看