Search Insert Position

来源:互联网 发布:贵州省茶叶出口数据 编辑:程序博客网 时间:2024/05/16 12:46

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

public class Solution {    public int searchInsert(int[] A, int target) {        if(A.length==0) return 0;        else if(target>A[A.length-1]) return A.length;        else if(target<A[0]) return 0;        else return bs(A,target);    }    public int bs(int []A,int target){        int l=0;        int r=A.length-1;        while(l<=r){            int mid=(l+r)/2;            if(A[mid]<target){                l=mid+1;            }            else if(A[mid]>target){                r=mid-1;            }            else{                return mid;            }        }        return l;    }}

0 0