zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):035-Search Insert Position


    题目来源

    https://leetcode.com/problems/search-insert-position/

    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.


    题意分析


    Input: a sorted list of int

    Output: the index if the target is found. If not, return the index where it would be if it were inserted in order.

    Conditions:找到target所在的位置或者应该插入的位置

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0


    题目思路


    使用二分法找元素,如果找到直接返回index,如果不能找到,此时又first和last两个值,注意到target总是不小于nums[first],所以比较target和first即可,

    1. 如果target大于nums[first],返回first + 1
    2. 反之返回first

    注意到在二分法当中first可能会加1溢出数组,所以在上面步骤当中要在比较前加入判断first是否溢出数组


    AC代码(Python)


     1 _author_ = "YE"
     2 # -*- coding:utf-8 -*-
     3 
     4 class Solution(object):
     5     def searchInsert(self, nums, target):
     6         """
     7         :type nums: List[int]
     8         :type target: int
     9         :rtype: int
    10         """
    11         len1 = len(nums)
    12         first = 0
    13         last = len1
    14         while first < last:
    15             mid = (first + last) // 2
    16             if nums[mid] == target:
    17                 return mid
    18             elif nums[mid] < target:
    19                 first = mid + 1
    20             else:
    21                 last = mid - 1
    22         # print(first,last)
    23         if first < len1 and nums[first] < target:
    24             return first + 1
    25         return first
    26 
    27 s = Solution()
    28 nums = [1,3]
    29 target = 2
    30 print(s.searchInsert(nums, target))
  • 相关阅读:
    SVD singular value decomposition
    Eigen参考资料
    设置C++ cout输出精度
    eigenMatrix
    电池容量单位 Wh和 Ah的关系
    windows10 如何关闭快速关机功能电源选项
    TIA Portal 和 scout 之间的驱动器地址分配
    SIMATIC 1500 PLC 同步轴,状态字StatusWord信号描述
    Simotion 凸轮同步,偏移凸轮起点
    ROS Create a Catkin Workspace
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5010446.html
Copyright © 2011-2022 走看看