【leetcode hot 100 35】搜索插入位置
解法一:二分查找法
class Solution {
public int searchInsert(int[] nums, int target) {
int n = nums.length;
int left = 0, right = n - 1, location = n;
while(left<=right){
int mid = (left+right)/2;
if(nums[mid]>=target){
location = mid;
right = mid-1;
}
else{
left = mid+1;
}
}
return location;
}
}
注意:
location
初始化为n
,当nums[mid]>=target
时更新为mid
- 循环终止条件为
left<=right
- 用
mid
更新时,要记得+1 -1 - 时间复杂度为 O(log n) 的算法 -> 二分查找
int mid = (left+right)/2
每次都取中间或者中间左边的那个数int mid = (left+right+1)/2
每次都取中间或者中间右边的那个数