首页 > 其他 > 详细

Leetcode Search Insert Position

时间:2015-02-03 20:56:33      阅读:176      评论: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.

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 }

 

Leetcode Search Insert Position

原文:http://www.cnblogs.com/criseRabbit/p/4270873.html

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