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
    
  • 相关阅读:
    分享ASP.NET+jQuery MiniUI后台购物管理
    ASP.NET发送电子邮件
    LINQ学习(三):Where子句
    ASP.NET配置KindEditor文本编辑器
    一步步写自己SqlHelper类库(五):Command对象
    ASP.NET生成静态页面的简单实现
    兼职开发悟出的点点滴滴
    设计模式学习笔记
    if else替代者
    ASP.NET 一生命周期中的额事件
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14008388.html
Copyright © 2011-2022 走看看