gpt4 book ai didi

python - 3SUM 到特定值

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

我目前有一个解决方案,但仍然慢了大约 300%。问题是从给定列表中找到总和为 n 的三个数字的子集。

goal = int(input().split()[1]) #The desired sum
numbers = list(map(int, input().split())) #User-inputted numbers

myDict = {} #Created so we can quickly check if a number is present in the list

for i in numbers: #The amount of each number is stored in the dict, eg. 439797: 2
if i in myDict:
myDict[i] += 1
else:
myDict[i] = 1


numbers = sorted(numbers)


for start in range(0, len(numbers)):
for end in range(1, len(numbers)):
myDict[numbers[start]] -= 1
myDict[numbers[end]] -= 1
#This is done so that the same number isn't used twice
if goal-numbers[start]-numbers[end] in myDict:
if myDict[goal-numbers[start]-numbers[end]] > 0:
print(goal-numbers[start]-numbers[end], numbers[start], numbers[end])
quit()
myDict[numbers[start]] += 1
myDict[numbers[end]] += 1

最佳答案

我完全同意 shinobi 的观点,但如果您需要快速计算这类任务,C++ 是最佳选择。代码如下所示:

for (int i = 0, i < len(numbers); i++) {
int m = numbers[i];
for (int j = i + 1, j < len(numbers); j++) {
int n = numbers[j];
if (n != m) {
int k = goal - m - n;
if (k != m && k != n && myDict[k]) {
doSomething();
}
}
}

关于python - 3SUM 到特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51080191/

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