0%

search-insert-position

Search Insert Position – LeetCode 35

Problem

Description

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,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

Answer

Original

Code

1
2
3
4
5
6
7
8
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
for(unsigned pos = 0; pos != nums.size(); ++pos)
if(nums[pos] >= target) return pos;
return nums.size();
}
};

思路

最简单的线性遍历,就是展示下。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$6$ ms,排名$66.33\%$

Better

思路

基础的二分查找,时间复杂度$O(\log_{2}{n})$,空间复杂度$O(1)$。
耗时$6$ ms,排名$66.33\%$

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int min = 0, max = nums.size() - 1;
while(min <= max){
int mid = min + (max - min) / 2;
if(nums[mid] == target){
return mid;
}
if(nums[mid] > target){
max = mid - 1;
} else {
min = mid + 1;
}
}
return min;
}
};