标签:
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