c++ - 有没有更有效的方法来检查列表中的两个数字是否相加为 int, k?

标签 c++ performance

我订阅了编码挑战邮件列表。这是今天的:

Given a list of numbers and a number k, return whether any two numbers from the list add up to k.

For example, given[10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

Bonus: Can you do this in one pass?

我想到了以下方法,但我想知道这是否是最有效的解决方案。

bool found = false;
int k = 17;
list<int> given({10, 15, 3, 7});

int main() {
    for (int num : given) {
        found = find(given.begin(), given.end(), k - num) != given.end();

        if (found) break;
    }

    return found;
}

代码完美运行。我只想知道它是否可以更有效率或 如果我在我的代码中做任何在工作场所不受欢迎的事情。非常感谢。

最佳答案

您可以使用集合对数组进行一次迭代。

int k = 17;
list<int> given({10, 15, 3, 7});
unordered_set<int> seen();

// O(n) time-complexity
int main() {
    // Iterate over O(n) items
    for (int num : given) {
        // O(1) operations
        if (seen.contains(k - num)) {
            // seen contains a value that is the difference between k and num. If you add num to that value, k - n + n = k, you have found two numbers that sum to k
            return true;
        } else {
            // Better luck next time, keep looking
            seen.add(num);
        }
    }

    return false;
}

关于c++ - 有没有更有效的方法来检查列表中的两个数字是否相加为 int, k?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667044/

相关文章:

c++ - 为什么不为将析构函数定义为 =default 的类合成移动操作?

c++ - 有多少种生成临时对象/不必要地调用构造函数的方法?

performance - JMeter Distributed Runner 无法生成合并报告

c++ - Loadlibrary excatly #import 做什么?

c++ - 同类数值类型之间的转换

c++ - 为什么 CMake COMPILER_DEFINITIONS 不传播到子目录?

mysql - MySQL 中使用 group by 查询 SQL 运行缓慢

c++ - 无限循环的形式不好吗?

python - 基于用户历史推荐产品的高效库

php - Doctrine2 性能 : Insert/Update multiple rows