arrays - 确定数组中是否存在 a、b、c 以使 a+b+c = z 的算法?

标签 arrays algorithm sum element

<分区>

在为以下问题寻找有效算法时遇到了一点困难。该算法必须确定数组中是否有 3 个元素 a、b 和 c,以便 a+b+c 等于给定的数字 z。

当然,天真的方法是尝试组合,但渐近所需的时间会太大。

要在数组中找到 a 和 b 使总和为 z 要容易得多。按升序对给定数组进行排序,并检查每个元素是否存在 z-a。但我不确定如何在 3 元素问题中实现它以及需要什么时间。

非常感谢任何帮助!

编辑:a、b、c 和 z 是整数。

最佳答案

该方法与求 a 和 b 的和 z 非常相似。

首先对数组进行排序。然后将 a 固定在位置 i 并检查是否在 i + 1 到 n

范围内有 sumz-a

因为你有一个 O(n) 算法来检查 z 是否存在 ab。我们只扩展它来修复 a 并检查是否可以使用另外两个变量来产生总和。总运行时间为 O(n^2)

来自 here

// returns true if there is triplet with sum equal
// to 'sum' present in A[]. Also, prints the triplet
bool find3Numbers(int A[], int arr_size, int sum)
{
    int l, r;

    /* Sort the elements */
    sort(A, A+arr_size);

    /* Now fix the first element one by one and find the
       other two elements */
    for (int i=0; i<arr_size-2; i++)
    {

        // To find the other two elements, start two index
        // variables from two corners of the array and move
        // them toward each other
        l = i + 1; // index of the first element in the
                   // remaining elements
        r = arr_size-1; // index of the last element
        while (l < r)
        {
            if( A[i] + A[l] + A[r] == sum)
            {
                printf("Triplet is %d, %d, %d", A[i], 
                                         A[l], A[r]);
                return true;
            }
            else if (A[i] + A[l] + A[r] < sum)
                l++;
            else // A[i] + A[l] + A[r] > sum
                r--;
        }
    }

    // If we reach here, then no triplet was found
    return false;
}

关于arrays - 确定数组中是否存在 a、b、c 以使 a+b+c = z 的算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122970/

相关文章:

python - 在 python 中处理字节

java - 打印出斐波那契数列

algorithm - 矩阵中要删除的最小列以使其按行字典顺序排序

matrix - 当给定行和列的总和时确定矩阵的元素

mysql - 计算用户点 - 更新与选择

arrays - 如果有多个条件则求和

arrays - Mongo 查询 - 推送唯一项并保留数组中的顺序

javascript - 对象到数组(数组的数组)

c++ - 从 0 到最大值的 uint64_t 键的最佳哈希函数是什么?

algorithm - 存在大小为 NxN 的 Hadamard 矩阵