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)

 

posted @ 2015-08-04 16:04  曾可爱  阅读(131)  评论(0编辑  收藏  举报