c++ - 在数组中找到四个元素,其总和等于给定数字 X

标签 c++ c algorithm

<分区>

我需要帮助来找到一个算法:

  • 数组中的四个元素
  • 总和等于给定数X
  • 复杂度为 O(n^2*log(n))

更喜欢伪代码或c、c++

最佳答案

您可以在 O(n^2) 中完成。适用于重复和负数。

edit 正如 Andre 在评论中指出的那样,时间与哈希的使用有关,它具有“最坏情况”(尽管它比中彩票的可能性要小)。但您也可以用平衡树(Java 中的 TreeMap)替换哈希表并获得稳定的 O(n^2 * log(n)) 解决方案。

Hashtable sums 将存储两个不同元素的所有可能的总和。对于每个和 S,它返回一对索引 ij 使得 a[i] + a[j] == S i != j。但最初它是空的,我们会在途中填充它。

for (int i = 0; i < n; ++i) {
    // 'sums' hastable holds all possible sums a[k] + a[l]
    // where k and l are both less than i

    for (int j = i + 1; j < n; ++j) {
        int current = a[i] + a[j];
        int rest = X - current;
        // Now we need to find if there're different numbers k and l
        // such that a[k] + a[l] == rest and k < i and l < i
        // but we have 'sums' hashtable prepared for that
        if (sums[rest] != null) {
            // found it
        }
    }

    // now let's put in 'sums' hashtable all possible sums
    // a[i] + a[k] where k < i
    for (int k = 0; k < i; ++k) {
        sums[a[i] + a[k]] = pair(i, k);
    }
}

比方说,X = a[1] + a[3] + a[7] + a[10]。当 i = 7j = 10rest = a[1] + a[3](索引 1 和3将从哈希中找到)

关于c++ - 在数组中找到四个元素,其总和等于给定数字 X,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3569504/

相关文章:

c++ - 不使用 for 循环传递数据

c++ - 替换现有条目并在 std::map 中添加新条目

c - 需要有关 C 中函数指针的建议

c - 我的输出不稳定

我相信我的子进程死得太快而无法运行我的信号?

python - 终止条件为 `left < right` 时的二分查找,步长更新为 `left = mid +1, right = mid`

python - python中的序列化字符串PK

Ruby 初学者 - 需要帮助优化此代码

c++ - MATLAB Wrapper 中的 MEX 代码

c++ - 第一次尝试 - 图形程序