4.搜索插入位置
一、题目
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
二、示例
输入: nums = [1,3,5,6], target = 5
输出: 2
三、代码实现
未修改版
public static int searchInsert(int[] nums,int target){
int n = nums.length;
int left = 0,right = n - 1;
while (left <= right){
int mid = (rigth+left)/2;
if (target <= nums[mid]){
n = mid;
right = mid - 1;
}else {
left = mid + 1;
}
}
return n;
}
优化版
public static int searchInsert(int[] nums,int target){
int left = 0,right = nums.length - 1;
while (left <= right){
int mid = left + (right - left)/2;
if (target <= nums[mid]){
right = mid - 1;
}else {
left = mid + 1;
}
}
return left;
}
优化主要体现在mid的赋值以及返回的值,
①mid赋值由(left+right)/2 改为 left + (right - left) / 2
赋值结果一样,但多次测试后发现后者内存消耗比前者小
②返回的值,由一个定义的值变为左指针,原因在于找到目标值后left不会更改
四、复杂度分析
时间复杂度:O(\log n)O(logn),其中 nn 为数组的长度。二分查找所需的时间复杂度为 O(\log n)O(logn)。
空间复杂度:O(1)O(1)。我们只需要常数空间存放若干变量。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position