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

Leetcode Search Insert Position

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