首页 > 其他 > 详细

Search Insert Position

时间:2015-09-03 06:58:09      阅读:257      评论:0      收藏:0      [点我收藏+]

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.

Example

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

Challenge

O(log(n)) time

 

Solution 1

 Naively, we can just iterate the array and compare target with ith and (i+1)th element. Time complexity is O(n)

 1 public int searchInsert(int[] A, int target) 
 2     {
 3         // write your code here
 4      if(A.length==0) return 0;
 5  
 6         if(target <= A[0]) return 0;
 7  
 8         for(int i=0; i<A.length-1; i++){
 9             if(target > A[i] && target <= A[i+1]){
10                 return i+1;
11             }
12         }
13  
14         return A.length;
15         
16     }

 

Solution 2

 This also looks like a binary search problem. We should try to make the complexity to be O(log(n)).

 1     public int searchInsert(int[] A, int target) 
 2     {
 3         // write your code here
 4      if(A.length==0) return 0;
 5      return helper(A, target, 0, A.length-1);
 6         
 7     }
 8     
 9     
10     public int helper(int[] A, int target, int start, int end)
11     {
12         int mid = (start+end)/2;
13         
14         if (target == A[mid]) return mid;
15         
16         if(target<A[mid])
17         {
18             if (mid <= start) return start;
19             else
20             {
21                 return helper(A,target,start,mid-1);
22             }
23         }
24         
25         else  //target > A[mid]
26         {
27             if(mid >= end) return end+1;
28             else
29             {
30                 return helper(A,target,mid+1,end);
31             }
32         }
33         
34         
35     }

 

reference: http://www.programcreek.com/2013/01/leetcode-search-insert-position/

Search Insert Position

原文:http://www.cnblogs.com/hygeia/p/4779852.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!