棘手的链表问题
给定三个列表:A、B 和 C,每个列表的长度为 n。如果任意 3 个数字(每个列表中 1 个),总和为零返回 true。我想用 o(n) 复杂度解决这个问题。我已经对列表进行了排序,我可以考虑创建一个总和为 2 的哈希映射链接列表或比较 3 个列表[o(n*n*n)]。建议一些即兴创作方法以降低复杂性的方法。我想不出任何方法...谢谢 adv
Given three lists: A, B and C of length n each. if any 3 three numbers (1 from each list), sum up to zero return true.I want to solve this with o(n)complexity.I have sorted the lists and I can think of creating either a hash map with sum of 2 linked lists or comparing 3 lists together[o(n*n*n)].Suggest some ways to improvise the methods to reduce complexity..I can't think of any...Thanks in adv
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
列表已排序,对吗?在 O(n) 时间内从 C 构建一个排序数组 C'。
对于 A × B 中的每一个 n² 对 x、y,使用二分查找检查 -(x + y) 是否在 C' 中。总时间复杂度为 O(n² lg n),空间复杂度为 O(n)。
用C构建哈希表可以将时间复杂度进一步降低到O(n²),但代价是对O(1)哈希表的信任。
The lists are sorted, right? Build a sorted array C' out of C in O(n) time.
For each of the n² pairs x, y in A × B, check if -(x + y) is in C' with binary search. Total time complexity is O(n² lg n), space complexity is O(n).
Building a hash table out of C brings the time complexity down further to O(n²), at the expense of belief in O(1) hash tables.
我认为在
o(n²)
中不可能(即确实比n²
更好),但可以在中完成O(n²)
(即n²
)如下:首先,反转列表
B
以获得B'
(需要O(n)
时间),其项目按降序排序的列表。首先,我们考虑在列表A
和B'
中查找两个元素的总和为任意给定数字的问题:我们可以像下面这样执行此操作(Python 代码):
上述的运行时间是
O(n)
。所需的额外空间是O(1)
,因为我们只需要存储两个指针。请注意,上面的内容可以很容易地进行转换,以便它可以与双向链表一起使用。然后,总的来说,我们只需执行以下操作:
这会导致运行时间
O(n²)
和额外的空间O(1)
。I do not think it is possible in
o(n²)
(i.e. really better thann²
), but it can be done inO(n²)
(i.e. sth. liken²
) as follows:First of all, reverse list
B
to obtainB'
(takesO(n)
time), a list whose items are sorted in descending order. First, we consider the problem of finding two elements in the listsA
andB'
that sum to any given number:We can do this like the following (Python code):
Run time of the above is
O(n)
. Additional space required isO(1)
since we only have to store two pointers. Note that the above can be easily transformed such that it works with doubly linked lists.Then, overall we just have to do the following:
That results in running time
O(n²)
and additional spaceO(1)
.你不能用 O(n) 的复杂度来做到这一点,因为它是 NP 完全问题(除非 P=NP)。请查看有关子集和问题的 Wiki 页面以获取可能的解决方案。
You can't do this with O(n) complexity since it's NP-complete problem (unless P=NP). Check out Wiki page about Subset Sum problem for possible solutions.