python - 3SUM 到特定值

标签 python algorithm subset-sum

我目前有一个解决方案,但仍然慢了大约 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/

相关文章:

python - 从 PyCharm IDE 启动时如何在 PyQt5 中使用 QOpenGLWidget 而不会卡住应用程序?

c++ - 使用每一行的二维数组中小于或等于 k ​​的最大可能总和

java - 具有一些额外条件的子集和算法的复杂性

algorithm - 纯函数式编程的效率

arrays - 找到最长的子数组

arrays - 找到所需元素的最小数量,使其总和等于或超过 S

algorithm - 查找对应于总和列表的一组对

python - pip:没有模块名称_internal.main

python - 导入错误 : cannot import name wsgiserver

python - 记录值可能有 unicode 错误的 python 字典