0%

[Leetcode]35. Search Insert Position(C++)

题目描述

题目链接:35. Search Insert Position

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.

例子

例子 1

Input: nums = [1,3,5,6], target = 5
Output: 2

例子 2

Input: nums = [1,3,5,6], target = 2
Output: 1

例子 3

Input: nums = [1,3,5,6], target = 7
Output: 4

Follow Up

Note

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order.
  • -10^4 <= target <= 10^4

解题思路

首先检查数组最大值是否比目标小,如果是直接返回数组长度即可。否则是二分查找进行搜索,这里注意,当二分查找找到目标时可以可以直接返回,但如果目标值存在的话,最后二分查找会停在左右两个值,右边大于目标值,左边小于目标值。这个时候目标值插入的位置应该是右侧边界,因此我们在收缩边界的时候方法是:需要收缩左边界时,让 left = mid + 1;收缩右边界时则让 right = mid,这样可以保证最后收缩在第一个比 target 更大的值。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
if (nums.size() == 0 || nums.back() < target) {
return nums.size();
}

size_t left = 0;
size_t right = nums.size() - 1;
while (left < right) {
size_t mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}

return left;
}
};
  • 时间复杂度: O(logN)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 35.SearchInsertPosition.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions