zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】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.

    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

    思路


           这道题最简单的思路就是从头开始查找,直到找到第一个大于等于target的位置。时间复杂度为O(n),空间复杂度为O(1)。

      第二种思路就是利用二分查找的思路,我们在数组中找到第一个大于等于target的位置,然后就是插入位置。时间复杂度为O(log n), 空间复杂度为O(1)。

    解决代码


     1 class Solution(object):
     2     def searchInsert(self, nums, target):
     3         """
     4         :type nums: List[int]
     5         :type target: int
     6         :rtype: int
     7         """
     8         if len(nums) < 1:
     9             return 
    10         start, end = 0, len(nums)-112         while start <= end:
    13             mid = start +((end -start)>>1)
    14             if nums[mid] < target:           # nums[middle]小于target时,移动指针位置.
    15                 start = mid+1
    16             else:                           # 当我们找到等于或者大于target时,判断以下当前下标位置以及,上一个元素是否小于target
    17                 if mid == 0 or nums[mid-1] <target:
    18                     return mid
    19                 end =  mid -1
    20         return start              # 返回开始位置    
  • 相关阅读:
    杂谈:用 Sublime Text 2 写 ActionScript3
    Sublime写MarkDown实时预览
    Cocos2d-Lua (练手) 微信打飞机
    Lua 性能相关笔记
    Lua 学习笔记(十一)元表与元方法
    Lua 学习笔记(十)数据结构
    Lua 学习笔记(九)协同程序(线程thread)
    Lua 学习笔记(八)错误(error)
    Lua 学习笔记(七)编译、执行外部代码块
    Lua 学习笔记(六)迭代器
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10684756.html
Copyright © 2011-2022 走看看