35.Search Insert Position
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 int searchInsert(int[] nums, int target) {
for(int i = 0;i < nums.length; i++){
if(target <= nums[i]){
return i;
}
}
return nums.length;
}
第二种方法
//因为原数组是按顺序排列的,所以可以用折半查找方法
public int searchInsert1(int[] A, int target) {
int low = 0, high = A.length-1;
while(low<=high){
int mid = (low+high)/2;
if(A[mid] == target) return mid;
else if(A[mid] > target) high = mid-1;
else low = mid+1;
}
return low;
}