搜索插入位置

中英题面

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

  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.

 

  案例 1:

  输入: [1,3,5,6], 5
  输出: 2

  Example 1:

  Input: [1,3,5,6], 5
  Output: 2

 

  案例 2:

  输入: [1,3,5,6], 2
  输出: 1

  Example 2:

  Input: [1,3,5,6], 2
  Output: 1

 

  案例 3:

  输入: [1,3,5,6], 7
  输出: 4

  Example 3:

  Input: [1,3,5,6], 7
  Output: 4

 

  案例 4:

  输入: [1,3,5,6], 0
  输出: 0

  Example 4:

  Input: [1,3,5,6], 0
  Output: 0

 

 

  

算法
  使用二分查找,Python 3 似乎没有自带的这类函数,手写了一个,算法时间复杂度 O(logN)。
 
代码
 1 class Solution:
 2     def searchInsert(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: int
 7         """
 8         if (nums[0] >= target):
 9             return 0
10         hen = 0
11         tai = len(nums)
12         while (hen + 1 < tai):
13             mid = (hen + tai) // 2
14             if (nums[mid] < target):
15                 hen = mid
16             else:
17                 tai = mid
18         return tai

 

 
posted @ 2018-04-05 14:52  Efve  阅读(198)  评论(0编辑  收藏  举报