问题描述:
Given a sorted array (ascending order) of distinct integers 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.
一刷用暴力算法,线性时间复杂度:
class Solution {
public int searchInsert(int[] nums, int target) {
for (int i=0; i<nums.length; i++){
if ((nums[i] == target) || (nums[i]>target)){
return i;
}
}
//如果target大于最后一个数,那么之前的循环没法捕捉它,现在手动把它加在最后
return nums.length;
}
}
时间复杂度: O(n)
二刷用二叉搜索,代码如下:
class Solution {
public int searchInsert(int[] nums, int target) {
//step1: get the right_bound and left_bound
int left=0;
int right=nums.length-1;
//don't loop when left=right, leave this equal situation for the final decison after loop
//我习惯不把=加在循环条件里
while(left<right){
//这样计算mid绝对不会overflow
int mid=left+(right-left)/2;
//不够大?左标设为mid+1
if(nums[mid]<target){
left=mid+1;
}
//刚好?就是它了!
else if(nums[mid]==target){
return mid;
}
//超了?右标=mid (注意不是mid-1)
else{
right=mid;
}
}
//if we reach here, meaning left=right, then we must make a decison
//因为我没有在循环里处理left=right的问题,现在就要处理它:
//注:这里用left和right都一样,因为执行到这一步肯定有left=right
//若临界点刚好是目标值(范围缩小到最后,机会终于等来了)
if(nums[left]==target){
return left;
}
//若临界点小于目标值,则把这个值加在left后面
else if (nums[left]<target){
return left+1;
}
//若临界点大于目标值,则把这个值加在left前面(其实相当于占用left位置)
else{
return left;
}
}
}
时间复杂度: O(logn)