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))
  • 相关阅读:
    四则运算出题器
    四则运算出题网页
    四则运算自动生成器实现(python、wxpython、GUI)
    python 实现小学四则运算
    Process and Thread States
    COS AP-开启WPA后无法关联SSID!
    WLC MAC Filtering
    禅道--个人理解 简单介绍
    IDEA解决乱码
    avue 实现自定义列显隐并保存,并且搜索表单、form表单、crud列顺序互不影响。
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5010446.html
Copyright © 2011-2022 走看看