【发布时间】:2017-07-17 01:59:12
【问题描述】:
我在 4SUM 问题的变体方面遇到了一些问题。本质上,我们需要从 4 个 500 个整数的元组中选择一个数字,例如 i、j、k、l,例如 a、b、c、d ,这样i+j+k+l == 0。这些整数的范围从-20000 到20000。目前,我相信我的代码的时间复杂度为 O(n3)。根据我的导师的说法,这个时间复杂度可以进一步降低到 O(n2 log n) 或 O(n2 sup>) (通过使用哈希表或其他东西)。
不幸的是,如果这种哈希表方法是可行的方法,我不知道如何实现它。因此,如果有人能告诉我如何在 Python 3.5 中编写这个程序,我将不胜感激。 (PS。请尽量使用尽可能少的嵌套循环,没有一个是理想的)。
我在下面附上了我的代码以供参考。如果可以修改我当前的代码以降低其时间复杂度,请也通知我。
import collections
import itertools
def selection(a, b, c, d):
"""program has 4 main parts,
firstly, triple_sum finds possible 3sums in the list abc
secondly, is_iterable ensures that inputs of tuple length 1 (ie. not iterable) are made iterable
thirdly, main function determines if there exists possible a, b, c in abc that correspond to each d
fourthly, main function checks if only 1 of the 3 integers from triple_sum exist in each array"""
'''use sort O(n log n) to sort input array, then find possible 3sums in O(n^2)'''
def triple_sum(a, res):
a.sort()
positions = collections.defaultdict(set)
for i, n in enumerate(a):
positions[n].add(i)
for (i, ai), (j, aj) in itertools.combinations(enumerate(a), 2):
n = res - ai - aj
if positions[n].difference((i, j)):
return n, ai, aj
'''Ensure that all inputs are iterable'''
def is_iterable(x):
if isinstance(x, collections.Iterable):
return x
else:
return x,
a, b, c, d = is_iterable(a), is_iterable(b), is_iterable(c), is_iterable(d)
abc = a + b + c
abc = [i for i in abc]
'''find value of d which has corresponding a, b, c
and returns appropriate value if conditions are met'''
ans_a, ans_b, ans_c, ans_d = 0, 0, 0, 0
for i in d:
x = 0 - i
j = triple_sum(abc, x)
if j[0] in a and j[1] in b and j[2] in c:
ans_a, ans_b, ans_c, ans_d = j[0], j[1], j[2], i
break
elif j[0] in a and j[2] in b and j[1] in c:
ans_a, ans_b, ans_c, ans_d = j[0], j[2], j[1], i
break
elif j[1] in a and j[0] in b and j[2] in c:
ans_a, ans_b, ans_c, ans_d = j[1], j[0], j[2], i
break
elif j[1] in a and j[2] in b and j[0] in c:
ans_a, ans_b, ans_c, ans_d = j[1], j[2], j[0], i
break
elif j[2] in a and j[0] in b and j[1] in c:
ans_a, ans_b, ans_c, ans_d = j[2], j[0], j[1], i
break
elif j[2] in a and j[1] in b and j[0] in c:
ans_a, ans_b, ans_c, ans_d = j[2], j[1], j[0], i
break
else:
continue
return ans_a, ans_b, ans_c, ans_d
提前致谢:)
PS。如果有人需要更多说明或信息,请告诉我。
【问题讨论】:
-
我还没有完全理解这个问题。你能举一个(小)例子来说明你的目标吗?
-
例如,假设元组是 a = (5, 17, -8) b = (-13, 19) c = (6, -9, 10, 0) d = (-14 , 7) 那么解应该是 17, -13, 10, -14
标签: python algorithm hashtable big-o