描述
给定一个排序数组和一个目标值,如果在数组中找到目标值则返回索引。如果没有,返回到它将会被按顺序插入的位置。
你可以假设在数组中无重复元素。
样例
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
挑战
O(log(n)) time1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class Solution {
    /**
     * @param A: an integer sorted array
     * @param target: an integer to be inserted
     * @return: An integer
     */
    public static int searchInsert(int[] A, int target) {
        // write your code here
    	int i; 
    	for( i=0;i<A.length;i++)
    	 {
    		 if(A[i]>=target)
    			 break;
    	 }
    	return i;
    }
}
因为数组为有序数组,通过循环判断程序中的元素找到相同的返回,如果循环到比target数据大的元素,即返回第一个比他大的元素下标。