找到两个数的差为一个特定数

探讨如何在已排序数组中找到两个整数a和b,使得它们之间的差值等于给定的整数k。文章提供了一种线性时间复杂度的解决方案,并通过示例代码展示了解决方案的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer 'k' and an sorted array A (can consist of both +ve/-ve nos), output 2 integers from A such that a-b=k.
PS:
nlogn solution would be to check for the occurence of k-a[i] (using binary search) when you encounter a[i]. methods like hash consume space.

Is an O(n) solution with O(1) extraspace possible?


void fun(vector<int> &a, int key)
{
	int n = a.size();
	if (n < 2)
	{
		return;
	}

	key = abs(key);
	int p = 0;
	int q = 1;
	while (q < n)
	{
		if (a[q] - a[p] == key)
		{
			cout << p << " " << q << endl;
			return;
		}
		else if (a[q] - a[p] > key)
		{
			p++;
		}
		else
		{
			q++;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值