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) {
for (int i = 0; i < A.length; i++) {
if(A[i]==target)return i;
if(target>A[i]&&i<(A.length-1)&&target<A[i+1])return i+1;
if(target>A[A.length-1])return A.length;
if(target<A[0])return 0;
}
return 0;
}
}
其中对于taget的位置来说,有四个定位
1.正好等于数组中的值,返回该值的下表
2.在两个数组的值中间,却不属于这个数组,返回当前值的下标加一
3.小于数组最小值,返回下标0
4.大于数组最大值,返回数组长度
在for循环中对每个值都进行这四个判断,即可。