在 O(n*log(n)) 内查找具有给定总和和乘积的一对数组元素
设 A 是一个由 n 个正整数组成的数组,并且 ka 是给定的整数。
我正在寻找一种算法来查找数组中是否存在一对元素,使得 A[i] * A[j] == k
和 A[i] == A[j] + k
。如果存在这样的一对,算法应该返回它们的索引。
这是一个家庭作业,我们被告知有一个 O(n*log(n)) 解决方案。
Let A be an array of n positive integers, and k a given integer.
I'm looking for algorithm to find if there is a pair of elements in the array such thatA[i] * A[j] == k
and A[i] == A[j] + k
. If there is such a pair, the algorithm should return their index.
This is a homework exercise, and we're told that there is an O(n*log(n)) solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我首先想到的是:
遍历数组的时间复杂度为 O(n),在 Map 中查找键的时间复杂度为 O(log n)(假设您使用 TreeMap,在最好的情况下 HashMap 可能会更好)但在最坏的情况下更糟)
编辑:我想这只能回答a)但你明白了
First thing off the top of my head:
So it's O(n) to traverse the array, and O(log n) to look up the key in the Map (assuming you used a TreeMap, a HashMap could be better in the best case but worse in the worst case)
Edit: I guess that only answers a) but you get the idea
这是 Graphics Noob 的解决方案,有些澄清。
而且,它更像是 O(N)(假设哈希不会让我们失败),而不是 O(N*log(N))。
Here is somewhat clarified Graphics Noob's solution.
Also, it is more like O(N) (assuming hashing won't fail us), not O(N*log(N)).
使用nlog(n)排序
然后遍历数组
对于每个索引,我计算 A[j] 需要什么才能满足方程
检查数组中是否存在这样的值
O(nlogn) + O(N)*O(logn)
=O(nlogn)
use nlog(n) to sort
then itterate through the array
for each index i calculate what A[j] would need to be in order for the equation to be satisfied
check to see if theres such a value in the array
O(nlogn) + O(N)*O(logn)
=O(nlogn)
如果 k 是固定的,则有有限多个整数 x, y 使得 x*y = k。
对于每个因子 (x,y),迭代列表以确定 A[i] = x 或 A[i] = y。
总运行时间 = O(n) * k 的 # 个因子 = O(n) (确定性地,不是关于散列的假设)
该问题表明 A[i] 都是正数,因此 k 可以有限地分解 x + y = k也有很多方法,所以 O(n) 也是如此。
If k is fixed, then there are finitely many integers x, y such that x*y = k.
For each factor (x,y), iterate through the list finding whether A[i] = x or A[i] = y.
Total run time = O(n) * # factors of k = O(n) (deterministically, not assumptions about hashing)
The problem states that A[i] are all positive, so k can be decomposed x + y = k in finitely many ways as well, so O(n) as well.