[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

posted @ 2015-10-28 19:47  Ry_Chen  阅读(721)  评论(1编辑  收藏  举报