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.
Hint: pay attention to the corner cases, line 6 to line 9. If the target is smaller than the first element, just return 0. If the target is greater than the last element, just return the length.[1,3,5,6], 5 → 2[1,3,5,6], 2 → 1[1,3,5,6], 7 → 4[1,3,5,6], 0 → 0
01 public int searchInsert(int[] A, int target) {
02
03 if(A.length==0) return 0;
04 if(target>A[A.length-1]) return A.length;
05
06 int start=0, end=A.length-1;
07
08 while(start<end)
09 {
10 int mid=start+(end-start)/2;
11
12 //find the target
13 if(A[mid]==target)
14 {
15 return mid;
16 }
17
18 else if(A[mid]<target)
19 {
20 start=mid+1;
21 }
22
23 else
24 {
25 end=mid;
26 }
27 }
28 return start;
29 }
02
03 if(A.length==0) return 0;
04 if(target>A[A.length-1]) return A.length;
05
06 int start=0, end=A.length-1;
07
08 while(start<end)
09 {
10 int mid=start+(end-start)/2;
11
12 //find the target
13 if(A[mid]==target)
14 {
15 return mid;
16 }
17
18 else if(A[mid]<target)
19 {
20 start=mid+1;
21 }
22
23 else
24 {
25 end=mid;
26 }
27 }
28 return start;
29 }
没有评论:
发表评论