[LeetCode] Search Insert Position

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.

You must write an algorithm with O(log n) runtime complexity.

1
2
3
4
5
6
7
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
}
};

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

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/search-insert-position/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.