Leetcode Search Insert Position

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

对于这道题其实比较简单,直接用二分查找法

 1 package Search.Insert.Position;
 2 
 3 public class SearchInsertPosition {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         //int[]A={1,3,5,6};
11         int []A={1,3,5,6};
12         SearchInsertPosition service=new SearchInsertPosition();
13         int a=service.searchInsert(A, 0);
14         System.out.println(a);
15         
16     }
17      public int searchInsert(int[] A, int target) {
18         int len=A.length;
19         int low=0;
20         int hi=len-1;
21         while(low<=hi){
22         int mid=(int)(low+hi)/2;
23         if(target==A[mid]){
24         return mid;    
25         }
26         if(target<A[mid]){
27             hi=mid-1;
28         }else{
29             low=mid+1;
30         }
31         }
32         return low;
33      }
34 }

 

posted on 2015-02-03 19:32  Chris兔的小佳佳  阅读(112)  评论(0)    收藏  举报