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
Analysis:
A typical binary search problem.
Solution:
1: public class Solution {
2: public int searchInsert(int[] A, int target) {
3: int high=A.length-1;
4: int low=0;
5: int mid=(high+low)/2;
6: while(low <=high)
7: {
8: mid=(high+low)/2;
9: if(target==A[mid])
10: return mid;
11: if(target>A[mid])
12: low=mid+1;
13: else
14: high=mid-1;
15: }
16: return low;
17: }
18: }
没有评论:
发表评论