gpt4 book ai didi

algorithm - sum = x 的数组中的 4 个值

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:03:52 26 4
gpt4 key购买 nike

我不需要这个代码。我想知道是否有人可以展示如何在大小为 n 的数组中找到 4 个整数,这些整数在时间复杂度 n^2logn 中可以等于值 x。我试着寻找视频,但发现它们很难跟上。据我了解,您创建了一个包含所有可能对的辅助数组?对它们进行排序,然后从较小的数组中找到 x 的总和?

例如。数组 = { 1,3,4,5,6,9,4}有人可以分步解释如何检查总和,比如 8。只需要帮助可视化这个过程。

最佳答案

# your input array 'df' and the sought sum 'x' 
df = [1,3,4,5,6,9,4]
x = 12

def findSumOfFour(df, x):
# create the dictionary of all pairs key (as sum of a pair) value (pair of indices of 'df')
myDict = { (df[i]+df[j]):[i,j] for i in range(0,len(df)) for j in range(i,len(df)) if not i == j}

# verify if 'x' - a key 'k' is again a key in the dictionary 'myDict',
# if so we only need to verify that the indices differ
for k in myDict.keys():
if x-k in myDict.keys() and not set(myDict[k]) & set(myDict[x-k]):
return [df[myDict[k][0]],df[myDict[k][1]],df[myDict[x-k][0]],df[myDict[x-k][1]]]

return []

solution = findSumOfFour(df,x)
print(solution)

请注意,此方法遵循 גלעד-ברקן 的描述(评论)更详细地解释了你的例子。

注意 2,运行时间在 O(n^2 log n) 中,因为 map /字典中的插入和查找操作通常是 O(log n)。

关于algorithm - sum = x 的数组中的 4 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com