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

    难度等级:简单

    题目描述:

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

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/search-insert-position
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解题思路:

    1、暴力解法,逐渐遍历对比,此方法时间复杂度是O(n)。

    2、二分法查找,笔者采用此方法,最快,时间复杂度是O(log n)

    解题代码:

    class Solution:
        def searchInsert(self, nums: List[int], target: int) -> int:
            left = 0
            right = len(nums) -1
            while True:
                index = int((left + right)/2)
                if target > nums[index]:  # 更新左右边界索引
                    left = index
                else:
                    right = index
    
                if len(nums[left: right])<=1:  # 退出循环,并得到索引位置
                    if target > nums[left] and target <= nums[right]:
                        rt = right
                    elif target > nums[right]:
                        rt = right + 1
                    elif target <= nums[left]:
                        rt = left
                    break
            return rt
  • 相关阅读:
    js 对象数组 排序
    sql 时间条件查询
    idea和Pycharm 等系列产品激活激活方法和激活码 100 年
    开源协议简介
    面试题
    VIM|基础命令
    git|基础命令
    VIM|复制
    lua|基础教程
    Printf格式输出详解
  • 原文地址:https://www.cnblogs.com/jaysonteng/p/12389770.html
Copyright © 2011-2022 走看看