STL low_bounded

该文章介绍了如何在有序整数数组中找到目标值的索引,如果目标值不存在,则返回其应被插入以保持有序状态的索引。解决方案是使用lower_bound函数,它具有O(logn)的时间复杂度。示例展示了在不同情况下,如何找到目标值的正确位置。
摘要由CSDN通过智能技术生成

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值