zoukankan      html  css  js  c++  java
  • LeetCode#35 Search Insert Position

    Problem Definition:

    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.

    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

    Solution:

    还是二分查找,注意返回插入位置的表示。

     1     # @param {integer[]} nums
     2     # @param {integer} target
     3     # @return {integer}
     4     def searchInsert(self, nums, target):
     5         return self.recur(nums, target, 0, len(nums)-1)
     6     
     7     def recur(self, nums, target, start, end):
     8         if start==end:
     9             if nums[start]>=target:
    10                 return start
    11             else:
    12                 return start+1
    13         else:
    14             mid=(start+end)/2
    15             if nums[mid]==target:
    16                 return mid
    17             elif nums[mid]>target:
    18                 return self.recur(nums, target, start, mid)
    19             else:
    20                 return self.recur(nums, target, mid+1, end)
  • 相关阅读:
    Python—设计模式
    Python—操作系统和多线程
    thin mission 2021 11 3
    搜索
    c++ 调试
    Lecture--words families
    高数--积分
    thin mission 2021.11.2
    tiny mission 2021.11.1
    zlib使用心得
  • 原文地址:https://www.cnblogs.com/acetseng/p/4702290.html
Copyright © 2011-2022 走看看