zoukankan      html  css  js  c++  java
  • LeetCode--035--搜索插入位置

    问题描述:

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

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

    方法1:for 循环

    class Solution(object):
        def searchInsert(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            if target > nums[-1]:
                return len(nums)
            for i in range(len(nums)):
                if nums[i] == target:
                    return i
                if nums[i] > target:
                    return i

    方法2:二分法查找

    class Solution(object):
        def searchInsert(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            start, end = 0, len(nums) - 1
            while start <= end:
                mid = (start + end) // 2
                if target == nums[mid]:
                    return mid
                if target < nums[mid]:
                    end = mid - 1
                else:
                    start = mid + 1
            return start

     2018-07-23 18:27:11

  • 相关阅读:
    讨论一下,乌云漏洞库的学习方法
    a
    asss
    密码重置
    SQL注入2
    起名字真难
    Header
    SQL注入1
    伪装者
    ofbiz 代码日记
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/9357025.html
Copyright © 2011-2022 走看看