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

    题目来源:

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


    题意分析:

      给定一个排好序的数组和一个target,如果target在数组里面,那么返回他的位置,否者返回他应该插入哪个位置。


    题目思路:

      这也是一个标准的二分查找。如果没有找到,那么和first和last位置的数比较一下就可以得到答案。


    代码(python):

      

     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         first = 0;last = len(nums) - 1
     9         while first < last:
    10             mid = (first + last + 1) // 2
    11             if nums[mid] == target:
    12                 return mid
    13             if nums[mid] < target:
    14                 first = mid + 1
    15             else:
    16                 last = mid - 1
    17         if nums[last] < target:
    18             return last + 1
    19         if target <= nums[last]:
    20             return last
    21         if target < nums[first]:
    22             return first
    23         return first + 1
    View Code

    转载请注明出处:http://www.cnblogs.com/chruny/p/4918447.html

  • 相关阅读:
    序言vue.js介绍
    python中end=''
    python文件的操作
    python异常
    python异常(理论知识)
    Uva 11300 Spreading the Wealth 中位数
    反转(开关问题) poj3276
    NEKO's Maze Game 思维
    Aaronson 一道思维题
    我开博客了
  • 原文地址:https://www.cnblogs.com/chruny/p/4918447.html
Copyright © 2011-2022 走看看