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
//直接查找:时间复杂度为O(n) ,runtime = 299ms
/*class Solution {
public int searchInsert(int[] nums, int target) {
int i = 0;
while (i < nums.length){
if (nums[i] >= target){
return i;
}
i ++;
}
return i;
}
}*/
//二分查找:时间复杂度为O(logn),runtime = 325ms
class Solution {
public int searchInsert(int[] nums, int target) {
int l = 0;
int h = nums.length - 1;
int mid = 0;
while (l <= h){
mid = (l + h) / 2;
if (nums[mid] == target){
return mid;
}
if (nums[mid] < target){
l = mid + 1;
}
else {
h = mid - 1;
}
}
return l;
}
}