Given a sorted array 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.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1
Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
示例 2:
输入: nums = [1,3,5,6], target = 2
输出: 1
示例 3:
输入: nums = [1,3,5,6], target = 7
输出: 4
一个待查找的数 是 整数, 且 知道范围
大概可以使用 二分查找算法
二分算法:
先设定左侧下标 left 和右侧下标 right,再计算中间下标 mid
每次根据nums[mid]和 target 之间的大小进行判断 相等则直接返回下标
nums[mid] < target 则 left 右移
nums[mid] > target 则 right 左移
思路 首先 思考 通过 数组 有序,寻找插入点
算法复杂度 要求 logn
判断 推测 极大概率 是考察 binary search
然后,创建 左指针
右指针
while循环 左指针 <= 右指针
计算mid
判断target 和 nums[mid] 之间的距离来 选择缩短边界
target <= nums[mid]
class Solution {
public int searchInsert(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
int mid;
while (l <= r){
mid = (l + r) >> 1;
if (target == nums[mid]){
return mid;
}
if (target > nums[mid]){
l = mid + 1;
} else {
r = mid - 1;
}
}
return l;
}
}
Reference
https://leetcode.cn/problems/search-insert-position



