![](/img/trans.png)
[英]Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K
[英]From 4 given arrays(not sorted), find the elements from each array whose sum is equal to some number X
假设有4个未排序的数组,如下所示:
A = [0, 100, -100, 50, 200]
B = [30, 100, 20, 0]
C = [0, 20, -1, 80]
D = [50, 0, -200, 1]
假设X为0,那么可能的O / P应该是少数(从每个满足条件的数组中选择1个元素):
0,0,0,0
-100, 100, 0, 0
-100, 30, 20,50 .. etc.
我能够设计出可以在O(n ^ 3LogN)中执行此操作的算法,有没有更好的方法来实现相同的目标?
我的解决方案
1-排序每个阵列。
2-修复了阵列A中的元素。
3-为其余数组运行三个循环并获取每个元素的总和:
if sum > 0 (return -1, no such elements exit)
if sum == 0 (return current elements)
if sum < 0 (then advance the pointer from the array for which the current element is minimum.)
有什么建议吗?
假设你的数组都具有相同的长度n
(+/-某个常数值),你可以通过使用第四个数组的set
得到O(n^3)
:
from itertools import product
ds = set(D)
for a, b, c in product(A, B, C):
d = X - a - b - c
if d in ds:
print(a, b, c, d)
如果一个或多个数组包含(许多)极值,您还可以通过检查后续数组的min
和max
的运行总和来查看快捷键,以查看是否仍然可以访问X
例如:
ds = set(D)
c_min, c_max = min(C), max(C)
d_min, d_max = min(ds), max(ds)
for a in A:
for b in B:
s = a + b
if s + c_min + d_min > X or s + c_max + d_max < X:
continue # Shortcut here.
for c in C:
d = X - a - b - c
if d in ds:
print(a, b, c, d)
您可以通过存储已经找到的运行总和(例如前两个数组)的解决方案来进一步扩展这一点,并因此在再次遇到这样的总和时采用快捷方式(通过使用最小/最大检查重新排序可以避免重复计算s + min / max值):
ds = set(D)
c_min, c_max = min(C), max(C)
d_min, d_max = min(ds), max(ds)
shortcuts = {}
for a in A:
for b in B:
s = a + b
if s in shortcuts:
for c, d in shortcuts[s]:
print(a, b, c, d)
continue
shortcuts[s] = []
if s + c_min + d_min > X or s + c_max + d_max < X:
continue
for c in C:
d = X - a - b - c
if d in ds:
print(a, b, c, d)
shortcuts[s].append((c, d))
对于A和B,我们可以通过哈希对和得到O(n^2)
,并检查对于它们中的任何一个, sum_AB[i]
可能在C和D的对中可能存在X - sum_AB[i]
哈希值。
在某些情况下,通过将每对列表乘以多项式中的系数计数,使用FFT得到O(m log m)
复杂度来枚举这些和可能更有效,其中m
是范围。
一种动态编程方法。
使用第一个列表A
初始化sums
(形式{possible_sum0: [way_to_get_sum0, ...]}
的形式的dict
)。 这导致了
sums = {0: [[0]], 100: [[100]], -100: [[-100]], 50: [[50]], 200: [[200]]}
用列表B
和C
更新该字典。 sums
现在将包含像
sums = {...,
30: [[0, 30, 0]],
50: [[0, 30, 20], [50, 0, 0]],
29: [[0, 30, -1]], ...}
然后在find_sum
我排序的最后名单D
和sums
对于一些加速和break
,如果一个给总和X
不再访问。
这是代码:
from collections import defaultdict
A = [0, 100, -100, 50, 200]
B = [30, 100, 20, 0]
C = [0, 20, -1, 80]
D = [50, 0, -200, 1]
def initialize_sums(lst):
return {item: [[item]] for item in lst}
def update_sums(sums, lst):
new_sums = defaultdict(list)
for sm, ways in sums.items():
for item in lst:
new_sum = sm + item
for way in ways:
new_sums[new_sum].append(way + [item])
return new_sums
def find_sum(sums, last_lst, X):
last_lst = sorted(last_lst)
ret = []
for sm, ways in sorted(sums.items()):
for item in last_lst:
x = sm + item
if x > X:
break
if x == X:
for way in ways:
ret.append(way + [item])
break
return ret
sums = initialize_sums(lst=A)
sums = update_sums(sums, lst=B)
sums = update_sums(sums, lst=C)
ret = find_sum(sums, last_lst=D, X=0)
print(ret)
# [[-100, 30, 20, 50], [0, 0, -1, 1], [-100, 100, -1, 1], ...]
......虽然没有分析整体复杂性。
找到数组的所有组合
def dOfSums(li):
return {sum(x):x for x in sum([list(itertools.combinations(li, i)) for i in range(2,len(li))],[])}
查找数组中数字的总和
def findSums(li, num):
return [((namestr(l), dOfSums(l)[num]) for l in li if num in dOfSums(l).keys() ]
命名数组
def namestr(obj):
return [name for name in globals() if globals()[name] is obj].pop()
测试
for el in findSums([A,B,C,D],50):
print(el)
('A', (0, 100, -100, 50))
('B', (30, 20, 0))
('D', (50, 0))
for el in findSums([A,B,C,D],100):
print(el)
('A', (0, -100, 200))
('B', (100, 0))
('C', (0, 20, 80))
for el in findSums([A,B,C,D],0):
print(el)
('A', (0, 100, -100))
A = [0, 100, -100, 50, 200]
B = [30, 100, 20, 0]
C = [0, 20, -1, 80]
D = [50, 0, -200, 1]
solutions = [(x1,x2,x3,x4) for x1 in A for x2 in B for x3 in C for x4 in D if sum([x1,x2,x3,x4]) == 0]
print(solutions)
输出:
>>>[(0, 0, 0, 0), (0, 0, -1, 1), (100, 100, 0, -200), (100, 20, 80, -200), (-100, 30, 20, 50), (-100, 100, 0, 0), (-100, 100, -1, 1), (-100, 20, 80, 0), (200, 0, 0, -200)]
这正是您在步骤中列出并适用于任何大小的内容,我不知道是否可以更轻松地找到针对不同列表大小的所有解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.