Leecode 0035. Search Insert Position
35. Search Insert Position
题目
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.
Example 1:
1 | Input: [1,3,5,6], 5 |
Example 2:
1 | Input: [1,3,5,6], 2 |
Example 3:
1 | Input: [1,3,5,6], 7 |
Example 4:
1 | Input: [1,3,5,6], 0 |
题目大意
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
核心思路
问题本质上是要找到第一个大于等于目标值的位置:
- 如果目标值存在于数组中,这个位置就是目标值的索引
- 如果目标值不存在,这个位置就是它应该插入的位置
算法步骤
- 初始化左右指针:
left = 0
,right = nums.size()
(使用左闭右开区间 [left, right)) - 计算中间位置
mid
,避免使用(left + right) / 2
以防整数溢出 - 比较中间值与目标值:
- 若
nums[mid] < target
,说明目标值应在右侧,调整left = mid + 1
- 否则,说明目标值应在左侧(包括当前位置),调整
right = mid
- 若
- 当
left == right
时,循环结束,此时left
就是目标位置
1 | #include <vector> |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.