码迷,mamicode.com
首页 > 其他好文 > 详细

Search Insert Position

时间:2015-09-03 07:01:23      阅读:197      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!