📌  相关文章
📜  找出总和为给定值的四个元素 |设置 3(哈希图)

📅  最后修改于: 2021-10-27 09:08:24             🧑  作者: Mango

给定一个整数数组,检查数组中不同索引处是否存在四个总和等于给定值 k 的元素。
例如,如果给定的数组是 {1 5 1 0 6 0} 并且 k = 7,那么您的函数应该将“YES”打印为 (1+5+1+0=7)。

例子:

Input  : arr[] = {1 5 1 0 6 0} 
             k = 7
Output : YES

Input :  arr[] = {38 7 44 42 28 16 10 37 
                  33 2 38 29 26 8 25} 
            k = 22
Output : NO

我们在以下两组中讨论了不同的解决方案。
找出总和为给定值的四个元素 |设置 1(n^3 解决方案)
找出总和为给定值的四个元素 |设置 2(O(n^2Logn) 解决方案)

在这篇文章中,讨论了一个平均在 O(n 2 ) 中工作的优化解决方案。

这个想法是创建一个哈希图来存储对和。

Loop i = 0 to n-1 :
 Loop j = i + 1 to n-1  
   calculate sum = arr[i] + arr[j]
     If (k-sum) exist in hash 
      a) Check in hash table for all
         pairs of indexes which form
         (k-sum).
      b) If there is any pair with no 
         no common indexes.
           return true 
    Else  update hash table
    EndLoop;
EndLoop;
// C++ program to find if there exist 4 elements
// with given sum
#include 
using namespace std;
  
// function to check if there exist four
// elements whose sum is equal to k
bool findfour(int arr[], int n, int k)
{
    // map to store sum and indexes for
    // a pair sum
    unordered_map > > hash;
  
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
  
            // calculate the sum of each pair
            int sum = arr[i] + arr[j];
  
            // if k-sum exist in map
            if (hash.find(k - sum) != hash.end()) {
                auto num = hash.find(k - sum);
                vector > v = num->second;
  
                // check for index coincidence as if
                // there is a common that means all
                // the four numbers are not from
                // different indexes and one of the
                // index is repeated
                for (int k = 0; k < num->second.size(); k++) {
  
                    pair it = v[k];
  
                    // if all indexes are different then
                    // it means four number exist
                    // set the flag and break the loop
                    if (it.first != i && it.first != j && 
                        it.second != i && it.second != j)
                        return true;
                }
            }
  
            // store the sum and index pair in hashmap
            hash[sum].push_back(make_pair(i, j));
        }
    }
    hash.clear();
    return false;
}
  
// Driver code
int main()
{
    int k = 7;
    int arr[] = { 1, 5, 1, 0, 6, 0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    if (findfour(arr, n, k))
        cout
            << "YES" << endl;
    else
        cout << "NO" << endl;
    return 0;
}

输出:

YES

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程