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.
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
Constraints:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104 nums contains distinct values sorted in ascending order.
- -104 <= target <= 104
AC:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
return lower_bound(nums.begin(),nums.end(),target) - nums.begin();
}
};
Vector – upper_bound and lower_bound
Iterator lower_bound (Iterator first, Iterator last, const val)
lower_bound returns an iterator pointing to the first element in the range [first,last) which has a value not less than ‘val’ and if the value is not present in the vector then it returns the end iterator.
Iterator upper_bound (Iterator first, Iterator last, const val)
upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘val’ and if the value is not present in the vector then it returns the end iterator.
// lower_bound and upper_bound in vector
#include <algorithm> // for lower_bound, upper_bound and sort
#include <iostream>
#include <vector> // for vector
using namespace std;
int main()
{
int gfg[] = { 5, 6, 7, 7, 6, 5, 5, 6 };
vector<int> v(gfg, gfg + 8); // 5 6 7 7 6 5 5 6
sort(v.begin(), v.end()); // 5 5 5 6 6 6 7 7
vector<int>::iterator lower, upper;
lower = lower_bound(v.begin(), v.end(), 6);
upper = upper_bound(v.begin(), v.end(), 6);
cout << "lower_bound for 6 at index "
<< (lower - v.begin()) << '\n';
cout << "upper_bound for 6 at index "
<< (upper - v.begin()) << '\n';
return 0;
}
output
lower_bound for 6 at index 3
upper_bound for 6 at index 6
Time Complexity: O(n*log(n)) where n is the number of elements in the
array. Auxiliary Space: O(1)