📌  相关文章
📜  找出总和为给定值的四个元素 | 2套

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

给定一个整数数组,找出数组中四个元素的总和等于给定值 X 的任意组合。

例如,

Input: array = {10, 2, 3, 4, 5, 9, 7, 8} 
       X = 23 
Output: 3 5 7 8
Sum of output is equal to 23, 
i.e. 3 + 5 + 7 + 8 = 23.

Input: array = {1, 2, 3, 4, 5, 9, 7, 8}
       X = 16 
Output: 1 3 5 7
Sum of output is equal to 16, 
i.e. 1 + 3 + 5 + 7 = 16.

我们在上一篇关于这个主题的文章中讨论了O(n 3 )算法。借助辅助空间,该问题可以在O(n 2 Logn)时间内解决。
感谢itsnimish 提出这种方法。以下是详细过程。

方法一:双指针算法。
方法:让输入数组为A[]。

  1. 创建一个辅助数组 aux[] 并将所有可能对的总和存储在 aux[] 中。 aux[] 的大小将为 n*(n-1)/2,其中 n 是 A[] 的大小。
  2. 对辅助数组 aux[] 进行排序。
  3. 现在问题简化为在 aux[] 中找到总和等于 X 的两个元素。我们可以使用本文的方法 1 高效地找到这两个元素。不过,有以下要点需要注意:
    aux[] 的元素代表来自 A[] 的一对。在从 aux[] 中选取两个元素时,我们必须检查这两个元素是否有共同的 A[] 元素。例如,如果 A[1] 和 A[2] 的第一个元素和,第二个元素是 A[2] 和 A[4] 的和,那么 aux[] 的这两个元素不代表四个不同的元素输入数组 A[]。

下面是上述方法的实现:

C++
// C++ program to find 4 elements
// with given sum
#include 
using namespace std;
 
// The following structure is needed
// to store pair sums in aux[]
class pairSum {
public:
    // index (int A[]) of first element in pair
    int first;
 
    // index of second element in pair
    int sec;
 
    // sum of the pair
    int sum;
};
 
// Following function is needed
// for library function qsort()
int compare(const void* a, const void* b)
{
    return ((*(pairSum*)a).sum - (*(pairSum*)b).sum);
}
 
// Function to check if two given pairs
// have any common element or not
bool noCommon(pairSum a, pairSum b)
{
    if (a.first == b.first || a.first == b.sec
        || a.sec == b.first || a.sec == b.sec)
        return false;
    return true;
}
 
// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    int i, j;
 
    // Create an auxiliary array
    // to store all pair sums
    int size = (n * (n - 1)) / 2;
    pairSum aux[size];
 
    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    int k = 0;
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            aux[k].sum = arr[i] + arr[j];
            aux[k].first = i;
            aux[k].sec = j;
            k++;
        }
    }
 
    // Sort the aux[] array using
    // library function for sorting
    qsort(aux, size, sizeof(aux[0]), compare);
 
    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0) {
        if ((aux[i].sum + aux[j].sum == X)
            && noCommon(aux[i], aux[j])) {
            cout << arr[aux[i].first] << ", "
                 << arr[aux[i].sec] << ", "
                 << arr[aux[j].first] << ", "
                 << arr[aux[j].sec] << endl;
            return;
        }
        else if (aux[i].sum + aux[j].sum < X)
            i++;
        else
            j--;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
   
    // Function Call
    findFourElements(arr, n, X);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C
// C program to find 4 elements
// with given sum
#include 
#include 
 
// The following structure is
// needed to store pair sums in aux[]
struct pairSum {
 
    // index (int A[]) of first element in pair
    int first;
 
    // index of second element in pair
    int sec;
 
    // sum of the pair
    int sum;
};
 
// Following function is needed
// for library function qsort()
int compare(const void* a, const void* b)
{
    return ((*(pairSum*)a).sum - (*(pairSum*)b).sum);
}
 
// Function to check if two given
// pairs have any common element or not
bool noCommon(struct pairSum a, struct pairSum b)
{
    if (a.first == b.first || a.first == b.sec
        || a.sec == b.first || a.sec == b.sec)
        return false;
    return true;
}
 
// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    int i, j;
 
    // Create an auxiliary array
    // to store all pair sums
    int size = (n * (n - 1)) / 2;
    struct pairSum aux[size];
 
    // Generate all possible pairs
    // from A[] and store sums
    // of all possible pairs in aux[]
    int k = 0;
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            aux[k].sum = arr[i] + arr[j];
            aux[k].first = i;
            aux[k].sec = j;
            k++;
        }
    }
 
    // Sort the aux[] array using
    // library function for sorting
    qsort(aux, size, sizeof(aux[0]), compare);
 
    // Now start two index variables
    // from two corners of array
    // and move them toward each other.
    i = 0;
    j = size - 1;
    while (i < size && j >= 0) {
        if ((aux[i].sum + aux[j].sum == X)
            && noCommon(aux[i], aux[j])) {
            printf("%d, %d, %d, %d\n", arr[aux[i].first],
                   arr[aux[i].sec], arr[aux[j].first],
                   arr[aux[j].sec]);
            return;
        }
        else if (aux[i].sum + aux[j].sum < X)
            i++;
        else
            j--;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
    
    // Function call
    findFourElements(arr, n, X);
    return 0;
}


C++
// A hashing based  CPP program
// to find if there are
// four elements with given sum.
#include 
using namespace std;
 
// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    // Store sums of all pairs
    // in a hash table
    unordered_map > mp;
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            mp[arr[i] + arr[j]] = { i, j };
 
    // Traverse through all pairs and search
    // for X - (current pair sum).
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int sum = arr[i] + arr[j];
 
            // If X - sum is present in hash table,
            if (mp.find(X - sum) != mp.end()) {
 
                // Making sure that all elements are
                // distinct array elements and an element
                // is not considered more than once.
                pair p = mp[X - sum];
                if (p.first != i && p.first != j
                    && p.second != i && p.second != j) {
                    cout << arr[i] << ", " << arr[j] << ", "
                         << arr[p.first] << ", "
                         << arr[p.second];
                    return;
                }
            }
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
    
    // Function call
    findFourElements(arr, n, X);
    return 0;
}


Java
// A hashing based Java program to find
// if there are four elements with given sum.
import java.util.HashMap;
class GFG {
    static class pair {
        int first, second;
        public pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
    }
 
    // The function finds four elements
    // with given sum X
    static void findFourElements(int arr[], int n, int X)
    {
        // Store sums of all pairs in a hash table
        HashMap mp
            = new HashMap();
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                mp.put(arr[i] + arr[j], new pair(i, j));
 
        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
 
                // If X - sum is present in hash table,
                if (mp.containsKey(X - sum)) {
 
                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    pair p = mp.get(X - sum);
                    if (p.first != i && p.first != j
                        && p.second != i && p.second != j) {
                        System.out.print(
                            arr[i] + ", " + arr[j] + ", "
                            + arr[p.first] + ", "
                            + arr[p.second]);
                        return;
                    }
                }
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 10, 20, 30, 40, 1, 2 };
        int n = arr.length;
        int X = 91;
       
        // Function call
        findFourElements(arr, n, X);
    }
}
 
// This code is contributed by Princi Singh


Python3
# A hashing based Python program to find if there are
# four elements with given summ.
 
# The function finds four elements with given summ X
 
 
def findFourElements(arr, n, X):
 
    # Store summs of all pairs in a hash table
    mp = {}
    for i in range(n - 1):
        for j in range(i + 1, n):
            mp[arr[i] + arr[j]] = [i, j]
 
    # Traverse through all pairs and search
    # for X - (current pair summ).
    for i in range(n - 1):
        for j in range(i + 1, n):
            summ = arr[i] + arr[j]
 
            # If X - summ is present in hash table,
            if (X - summ) in mp:
 
                # Making sure that all elements are
                # distinct array elements and an element
                # is not considered more than once.
                p = mp[X - summ]
                if (p[0] != i and p[0] != j and p[1] != i and p[1] != j):
                    print(arr[i], ", ", arr[j], ", ",
                          arr[p[0]], ", ", arr[p[1]], sep="")
                    return
 
 
# Driver code
arr = [10, 20, 30, 40, 1, 2]
n = len(arr)
X = 91
 
# Function call
findFourElements(arr, n, X)
 
# This is code is contributed by shubhamsingh10


C#
// A hashing based C# program to find
// if there are four elements with given sum.
using System;
using System.Collections.Generic;
 
class GFG {
    public class pair {
        public int first, second;
        public pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
    }
 
    // The function finds four elements
    // with given sum X
    static void findFourElements(int[] arr, int n, int X)
    {
        // Store sums of all pairs in a hash table
        Dictionary mp
            = new Dictionary();
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (mp.ContainsKey(arr[i] + arr[j]))
                    mp[arr[i] + arr[j]] = new pair(i, j);
                else
                    mp.Add(arr[i] + arr[j], new pair(i, j));
 
        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
 
                // If X - sum is present in hash table,
                if (mp.ContainsKey(X - sum)) {
 
                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    pair p = mp[X - sum];
                    if (p.first != i && p.first != j
                        && p.second != i && p.second != j) {
                        Console.Write(arr[i] + ", " + arr[j]
                                      + ", " + arr[p.first]
                                      + ", "
                                      + arr[p.second]);
                        return;
                    }
                }
            }
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 10, 20, 30, 40, 1, 2 };
        int n = arr.Length;
        int X = 91;
       
        // Function call
        findFourElements(arr, n, X);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ program to find four 
// elements with the given sum
#include 
using namespace std;
 
// Function to find 4 elements that add up to
// given sum
void fourSum(int X, int arr[], map> Map, int N)
{
    int temp[N];
 
    // Iterate from 0 to temp.length
    for (int i = 0; i < N; i++)
        temp[i] = 0;
 
    // Iterate from 0 to arr.length
    for (int i = 0; i < N - 1; i++)
    {
 
        // Iterate from i + 1 to arr.length
        for (int j = i + 1; j < N; j++)
        {
 
            // Store curr_sum = arr[i] + arr[j]
            int curr_sum = arr[i] + arr[j];
 
            // Check if X - curr_sum if present
            // in map
            if (Map.find(X - curr_sum) != Map.end())
            {
 
                // Store pair having map value
                // X - curr_sum
                pair p = Map[X - curr_sum];
 
                if (p.first != i && p.second != i
                    && p.first != j && p.second != j
                    && temp[p.first] == 0
                    && temp[p.second] == 0 && temp[i] == 0
                    && temp[j] == 0)
                {
 
                    // Print the output
                    cout << arr[i] << "," << arr[j] <<
                      "," << arr[p.first] << "," << arr[p.second];
                    temp[p.second] = 1;
                    temp[i] = 1;
                    temp[j] = 1;
                    break;
                }
            }
        }
    }
}
 
// Program for two Sum
map> twoSum(int nums[], int N)
{
    map> Map;
    for (int i = 0; i < N - 1; i++)
    {
        for (int j = i + 1; j < N; j++)
        {
            Map[nums[i] + nums[j]].first = i;
            Map[nums[i] + nums[j]].second = j;
        }
    }
    return Map;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
    map> Map = twoSum(arr, n);
     
    // Function call
    fourSum(X, arr, Map, n);
 
    return 0;
}
 
// This code is contributed by divyesh072019


Java
// Java program to find four
// elements with the given sum
import java.util.*;
 
class fourElementWithSum {
 
    // Function to find 4 elements that add up to
    // given sum
    public static void fourSum(int X, int[] arr,
                               Map map)
    {
        int[] temp = new int[arr.length];
 
        // Iterate from 0 to temp.length
        for (int i = 0; i < temp.length; i++)
            temp[i] = 0;
 
        // Iterate from 0 to arr.length
        for (int i = 0; i < arr.length - 1; i++) {
 
            // Iterate from i + 1 to arr.length
            for (int j = i + 1; j < arr.length; j++) {
 
                // Store curr_sum = arr[i] + arr[j]
                int curr_sum = arr[i] + arr[j];
 
                // Check if X - curr_sum if present
                // in map
                if (map.containsKey(X - curr_sum)) {
 
                    // Store pair having map value
                    // X - curr_sum
                    pair p = map.get(X - curr_sum);
 
                    if (p.first != i && p.sec != i
                        && p.first != j && p.sec != j
                        && temp[p.first] == 0
                        && temp[p.sec] == 0 && temp[i] == 0
                        && temp[j] == 0) {
 
                        // Print the output
                        System.out.printf(
                            "%d,%d,%d,%d", arr[i], arr[j],
                            arr[p.first], arr[p.sec]);
                        temp[p.sec] = 1;
                        temp[i] = 1;
                        temp[j] = 1;
                        break;
                    }
                }
            }
        }
    }
 
    // Program for two Sum
    public static Map twoSum(int[] nums)
    {
        Map map = new HashMap<>();
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                map.put(nums[i] + nums[j], new pair(i, j));
            }
        }
        return map;
    }
 
    // to store indices of two sum pair
    public static class pair {
        int first, sec;
 
        public pair(int first, int sec)
        {
            this.first = first;
            this.sec = sec;
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int[] arr = { 10, 20, 30, 40, 1, 2 };
        int n = arr.length;
        int X = 91;
        Map map = twoSum(arr);
       
        // Function call
        fourSum(X, arr, map);
    }
}
 
// This code is contributed by Likhita avl.


Python3
# Python3 program to find four 
# elements with the given sum
 
# Function to find 4 elements that
# add up to given sum
def fourSum(X, arr, Map, N):
     
    temp = [0 for i in range(N)]
     
    # Iterate from 0 to length of arr
    for i in range(N - 1):
         
        # Iterate from i + 1 to length of arr
        for j in range(i + 1, N):
             
            # Store curr_sum = arr[i] + arr[j]
            curr_sum = arr[i] + arr[j]
 
            # Check if X - curr_sum if present
            # in map
            if (X - curr_sum) in Map:
                 
                # Store pair having map value
                # X - curr_sum
                p = Map[X - curr_sum]
 
                if (p[0] != i and p[1] != i and
                    p[0] != j and p[1] != j and
                    temp[p[0]] == 0 and temp[p[1]] == 0 and
                    temp[i] == 0 and temp[j] == 0):
                         
                    # Print the output
                    print(arr[i], ",", arr[j], ",",
                          arr[p[0]], ",", arr[p[1]],
                          sep = "")
                           
                    temp[p[1]] = 1
                    temp[i] = 1
                    temp[j] = 1
                    break
 
# Function for two Sum
def twoSum(nums, N):
     
    Map = {}
     
    for i in range(N - 1):
        for j in range(i + 1, N):
            Map[nums[i] + nums[j]] = []
            Map[nums[i] + nums[j]].append(i)
            Map[nums[i] + nums[j]].append(j)
 
    return Map
 
# Driver code
arr = [ 10, 20, 30, 40, 1, 2 ]
n = len(arr)
X = 91
Map = twoSum(arr, n)
 
# Function call
fourSum(X, arr, Map, n)
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program to find four 
// elements with the given sum
using System;
using System.Collections.Generic; 
class GFG
{
     
    // Function to find 4 elements that add up to
    // given sum
    static void fourSum(int X, int[] arr, Dictionary> Map, int N)
    {
        int[] temp = new int[N];
      
        // Iterate from 0 to temp.length
        for (int i = 0; i < N; i++)
            temp[i] = 0;
      
        // Iterate from 0 to arr.length
        for (int i = 0; i < N - 1; i++)
        {
      
            // Iterate from i + 1 to arr.length
            for (int j = i + 1; j < N; j++)
            {
      
                // Store curr_sum = arr[i] + arr[j]
                int curr_sum = arr[i] + arr[j];
      
                // Check if X - curr_sum if present
                // in map
                if (Map.ContainsKey(X - curr_sum))
                {
      
                    // Store pair having map value
                    // X - curr_sum
                    Tuple p = Map[X - curr_sum];
      
                    if (p.Item1 != i && p.Item2 != i
                        && p.Item1 != j && p.Item2 != j
                        && temp[p.Item1] == 0
                        && temp[p.Item2] == 0 && temp[i] == 0
                        && temp[j] == 0)
                    {
      
                        // Print the output
                        Console.Write(arr[i] + "," + arr[j] +
                                      "," + arr[p.Item1] + "," +
                                      arr[p.Item2]);
                        temp[p.Item2] = 1;
                        temp[i] = 1;
                        temp[j] = 1;
                        break;
                    }
                }
            }
        }
    }
      
    // Program for two Sum
    static Dictionary> twoSum(int[] nums, int N)
    {
        Dictionary> Map =
          new Dictionary>();
        for (int i = 0; i < N - 1; i++)
        {
            for (int j = i + 1; j < N; j++)
            {
                Map[nums[i] + nums[j]] = new Tuple(i, j);
            }
        }
        return Map;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 10, 20, 30, 40, 1, 2 };
    int n = arr.Length;
    int X = 91;
    Dictionary> Map = twoSum(arr, n);
      
    // Function call
    fourSum(X, arr, Map, n);
  }
}
 
// This code is contributed by divyeshrabadiya07


Javascript


输出

20, 1, 30, 40

请注意,上面的代码只打印了一个四元组。如果我们删除 return 语句并添加语句“i++; j-;”,然后它会打印五次相同的四倍。可以修改代码以仅打印一次所有四元组。一直保持这种方式以保持简单。
复杂度分析:

  • 时间复杂度: O(n^2Logn)。
    第 1 步需要 O(n^2) 时间。第二步是对大小为 O(n^2) 的数组进行排序。可以使用归并排序或堆排序或任何其他 O(nLogn) 算法在 O(n^2Logn) 时间内完成排序。第三步需要 O(n^2) 时间。所以整体复杂度是 O(n^2Logn)。
  • 辅助空间: O(n^2)。
    辅助数组的大小为 O(n^2)。在这种方法中,辅助数组的大尺寸可能是一个问题。

方法 2:基于散列的解决方案[O(n 2 )]

方法:

  1. 将所有对的总和存储在哈希表中
  2. 再次遍历所有对并在哈希表中搜索X –(当前对和)
  3. 如果找到具有所需总和的对,则确保所有元素都是不同的数组元素,并且不会多次考虑一个元素。

下图是上述方法的试运行:

下面是上述方法的实现:

C++

// A hashing based  CPP program
// to find if there are
// four elements with given sum.
#include 
using namespace std;
 
// The function finds four
// elements with given sum X
void findFourElements(int arr[], int n, int X)
{
    // Store sums of all pairs
    // in a hash table
    unordered_map > mp;
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)
            mp[arr[i] + arr[j]] = { i, j };
 
    // Traverse through all pairs and search
    // for X - (current pair sum).
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int sum = arr[i] + arr[j];
 
            // If X - sum is present in hash table,
            if (mp.find(X - sum) != mp.end()) {
 
                // Making sure that all elements are
                // distinct array elements and an element
                // is not considered more than once.
                pair p = mp[X - sum];
                if (p.first != i && p.first != j
                    && p.second != i && p.second != j) {
                    cout << arr[i] << ", " << arr[j] << ", "
                         << arr[p.first] << ", "
                         << arr[p.second];
                    return;
                }
            }
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
    
    // Function call
    findFourElements(arr, n, X);
    return 0;
}

Java

// A hashing based Java program to find
// if there are four elements with given sum.
import java.util.HashMap;
class GFG {
    static class pair {
        int first, second;
        public pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
    }
 
    // The function finds four elements
    // with given sum X
    static void findFourElements(int arr[], int n, int X)
    {
        // Store sums of all pairs in a hash table
        HashMap mp
            = new HashMap();
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                mp.put(arr[i] + arr[j], new pair(i, j));
 
        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
 
                // If X - sum is present in hash table,
                if (mp.containsKey(X - sum)) {
 
                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    pair p = mp.get(X - sum);
                    if (p.first != i && p.first != j
                        && p.second != i && p.second != j) {
                        System.out.print(
                            arr[i] + ", " + arr[j] + ", "
                            + arr[p.first] + ", "
                            + arr[p.second]);
                        return;
                    }
                }
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 10, 20, 30, 40, 1, 2 };
        int n = arr.length;
        int X = 91;
       
        // Function call
        findFourElements(arr, n, X);
    }
}
 
// This code is contributed by Princi Singh

蟒蛇3

# A hashing based Python program to find if there are
# four elements with given summ.
 
# The function finds four elements with given summ X
 
 
def findFourElements(arr, n, X):
 
    # Store summs of all pairs in a hash table
    mp = {}
    for i in range(n - 1):
        for j in range(i + 1, n):
            mp[arr[i] + arr[j]] = [i, j]
 
    # Traverse through all pairs and search
    # for X - (current pair summ).
    for i in range(n - 1):
        for j in range(i + 1, n):
            summ = arr[i] + arr[j]
 
            # If X - summ is present in hash table,
            if (X - summ) in mp:
 
                # Making sure that all elements are
                # distinct array elements and an element
                # is not considered more than once.
                p = mp[X - summ]
                if (p[0] != i and p[0] != j and p[1] != i and p[1] != j):
                    print(arr[i], ", ", arr[j], ", ",
                          arr[p[0]], ", ", arr[p[1]], sep="")
                    return
 
 
# Driver code
arr = [10, 20, 30, 40, 1, 2]
n = len(arr)
X = 91
 
# Function call
findFourElements(arr, n, X)
 
# This is code is contributed by shubhamsingh10

C#

// A hashing based C# program to find
// if there are four elements with given sum.
using System;
using System.Collections.Generic;
 
class GFG {
    public class pair {
        public int first, second;
        public pair(int first, int second)
        {
            this.first = first;
            this.second = second;
        }
    }
 
    // The function finds four elements
    // with given sum X
    static void findFourElements(int[] arr, int n, int X)
    {
        // Store sums of all pairs in a hash table
        Dictionary mp
            = new Dictionary();
        for (int i = 0; i < n - 1; i++)
            for (int j = i + 1; j < n; j++)
                if (mp.ContainsKey(arr[i] + arr[j]))
                    mp[arr[i] + arr[j]] = new pair(i, j);
                else
                    mp.Add(arr[i] + arr[j], new pair(i, j));
 
        // Traverse through all pairs and search
        // for X - (current pair sum).
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int sum = arr[i] + arr[j];
 
                // If X - sum is present in hash table,
                if (mp.ContainsKey(X - sum)) {
 
                    // Making sure that all elements are
                    // distinct array elements and an
                    // element is not considered more than
                    // once.
                    pair p = mp[X - sum];
                    if (p.first != i && p.first != j
                        && p.second != i && p.second != j) {
                        Console.Write(arr[i] + ", " + arr[j]
                                      + ", " + arr[p.first]
                                      + ", "
                                      + arr[p.second]);
                        return;
                    }
                }
            }
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 10, 20, 30, 40, 1, 2 };
        int n = arr.Length;
        int X = 91;
       
        // Function call
        findFourElements(arr, n, X);
    }
}
 
// This code is contributed by 29AjayKumar

Javascript


输出
20, 30, 40, 1

复杂度分析:

  • 时间复杂度: O(n^2)。
    需要嵌套遍历将所有对存储在哈希 Map 中。
  • 辅助空间: O(n^2)。
    所有 n*(n-1) 对都存储在哈希 Map 中,因此所需的空间为 O(n^2)
    如果您发现上述任何代码/算法不正确,请写评论,或者找到其他方法来解决同样的问题。

方法三:没有重复元素的解决方案

方法:

  1. 将所有对的总和存储在哈希表中
  2. 再次遍历所有对并在哈希表中搜索 X –(当前对和)。
  3. 考虑一个最初用零存储的临时数组。当我们得到 4 个总和为所需值的元素时,它会更改为 1。
  4. 如果找到具有所需总和的对,则确保所有元素都是不同的数组元素,并检查临时数组中的值是否为 0,以便不考虑重复。

下面是代码的实现:

C++

// C++ program to find four 
// elements with the given sum
#include 
using namespace std;
 
// Function to find 4 elements that add up to
// given sum
void fourSum(int X, int arr[], map> Map, int N)
{
    int temp[N];
 
    // Iterate from 0 to temp.length
    for (int i = 0; i < N; i++)
        temp[i] = 0;
 
    // Iterate from 0 to arr.length
    for (int i = 0; i < N - 1; i++)
    {
 
        // Iterate from i + 1 to arr.length
        for (int j = i + 1; j < N; j++)
        {
 
            // Store curr_sum = arr[i] + arr[j]
            int curr_sum = arr[i] + arr[j];
 
            // Check if X - curr_sum if present
            // in map
            if (Map.find(X - curr_sum) != Map.end())
            {
 
                // Store pair having map value
                // X - curr_sum
                pair p = Map[X - curr_sum];
 
                if (p.first != i && p.second != i
                    && p.first != j && p.second != j
                    && temp[p.first] == 0
                    && temp[p.second] == 0 && temp[i] == 0
                    && temp[j] == 0)
                {
 
                    // Print the output
                    cout << arr[i] << "," << arr[j] <<
                      "," << arr[p.first] << "," << arr[p.second];
                    temp[p.second] = 1;
                    temp[i] = 1;
                    temp[j] = 1;
                    break;
                }
            }
        }
    }
}
 
// Program for two Sum
map> twoSum(int nums[], int N)
{
    map> Map;
    for (int i = 0; i < N - 1; i++)
    {
        for (int j = i + 1; j < N; j++)
        {
            Map[nums[i] + nums[j]].first = i;
            Map[nums[i] + nums[j]].second = j;
        }
    }
    return Map;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 20, 30, 40, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int X = 91;
    map> Map = twoSum(arr, n);
     
    // Function call
    fourSum(X, arr, Map, n);
 
    return 0;
}
 
// This code is contributed by divyesh072019

Java

// Java program to find four
// elements with the given sum
import java.util.*;
 
class fourElementWithSum {
 
    // Function to find 4 elements that add up to
    // given sum
    public static void fourSum(int X, int[] arr,
                               Map map)
    {
        int[] temp = new int[arr.length];
 
        // Iterate from 0 to temp.length
        for (int i = 0; i < temp.length; i++)
            temp[i] = 0;
 
        // Iterate from 0 to arr.length
        for (int i = 0; i < arr.length - 1; i++) {
 
            // Iterate from i + 1 to arr.length
            for (int j = i + 1; j < arr.length; j++) {
 
                // Store curr_sum = arr[i] + arr[j]
                int curr_sum = arr[i] + arr[j];
 
                // Check if X - curr_sum if present
                // in map
                if (map.containsKey(X - curr_sum)) {
 
                    // Store pair having map value
                    // X - curr_sum
                    pair p = map.get(X - curr_sum);
 
                    if (p.first != i && p.sec != i
                        && p.first != j && p.sec != j
                        && temp[p.first] == 0
                        && temp[p.sec] == 0 && temp[i] == 0
                        && temp[j] == 0) {
 
                        // Print the output
                        System.out.printf(
                            "%d,%d,%d,%d", arr[i], arr[j],
                            arr[p.first], arr[p.sec]);
                        temp[p.sec] = 1;
                        temp[i] = 1;
                        temp[j] = 1;
                        break;
                    }
                }
            }
        }
    }
 
    // Program for two Sum
    public static Map twoSum(int[] nums)
    {
        Map map = new HashMap<>();
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                map.put(nums[i] + nums[j], new pair(i, j));
            }
        }
        return map;
    }
 
    // to store indices of two sum pair
    public static class pair {
        int first, sec;
 
        public pair(int first, int sec)
        {
            this.first = first;
            this.sec = sec;
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int[] arr = { 10, 20, 30, 40, 1, 2 };
        int n = arr.length;
        int X = 91;
        Map map = twoSum(arr);
       
        // Function call
        fourSum(X, arr, map);
    }
}
 
// This code is contributed by Likhita avl.

蟒蛇3

# Python3 program to find four 
# elements with the given sum
 
# Function to find 4 elements that
# add up to given sum
def fourSum(X, arr, Map, N):
     
    temp = [0 for i in range(N)]
     
    # Iterate from 0 to length of arr
    for i in range(N - 1):
         
        # Iterate from i + 1 to length of arr
        for j in range(i + 1, N):
             
            # Store curr_sum = arr[i] + arr[j]
            curr_sum = arr[i] + arr[j]
 
            # Check if X - curr_sum if present
            # in map
            if (X - curr_sum) in Map:
                 
                # Store pair having map value
                # X - curr_sum
                p = Map[X - curr_sum]
 
                if (p[0] != i and p[1] != i and
                    p[0] != j and p[1] != j and
                    temp[p[0]] == 0 and temp[p[1]] == 0 and
                    temp[i] == 0 and temp[j] == 0):
                         
                    # Print the output
                    print(arr[i], ",", arr[j], ",",
                          arr[p[0]], ",", arr[p[1]],
                          sep = "")
                           
                    temp[p[1]] = 1
                    temp[i] = 1
                    temp[j] = 1
                    break
 
# Function for two Sum
def twoSum(nums, N):
     
    Map = {}
     
    for i in range(N - 1):
        for j in range(i + 1, N):
            Map[nums[i] + nums[j]] = []
            Map[nums[i] + nums[j]].append(i)
            Map[nums[i] + nums[j]].append(j)
 
    return Map
 
# Driver code
arr = [ 10, 20, 30, 40, 1, 2 ]
n = len(arr)
X = 91
Map = twoSum(arr, n)
 
# Function call
fourSum(X, arr, Map, n)
 
# This code is contributed by avanitrachhadiya2155

C#

// C# program to find four 
// elements with the given sum
using System;
using System.Collections.Generic; 
class GFG
{
     
    // Function to find 4 elements that add up to
    // given sum
    static void fourSum(int X, int[] arr, Dictionary> Map, int N)
    {
        int[] temp = new int[N];
      
        // Iterate from 0 to temp.length
        for (int i = 0; i < N; i++)
            temp[i] = 0;
      
        // Iterate from 0 to arr.length
        for (int i = 0; i < N - 1; i++)
        {
      
            // Iterate from i + 1 to arr.length
            for (int j = i + 1; j < N; j++)
            {
      
                // Store curr_sum = arr[i] + arr[j]
                int curr_sum = arr[i] + arr[j];
      
                // Check if X - curr_sum if present
                // in map
                if (Map.ContainsKey(X - curr_sum))
                {
      
                    // Store pair having map value
                    // X - curr_sum
                    Tuple p = Map[X - curr_sum];
      
                    if (p.Item1 != i && p.Item2 != i
                        && p.Item1 != j && p.Item2 != j
                        && temp[p.Item1] == 0
                        && temp[p.Item2] == 0 && temp[i] == 0
                        && temp[j] == 0)
                    {
      
                        // Print the output
                        Console.Write(arr[i] + "," + arr[j] +
                                      "," + arr[p.Item1] + "," +
                                      arr[p.Item2]);
                        temp[p.Item2] = 1;
                        temp[i] = 1;
                        temp[j] = 1;
                        break;
                    }
                }
            }
        }
    }
      
    // Program for two Sum
    static Dictionary> twoSum(int[] nums, int N)
    {
        Dictionary> Map =
          new Dictionary>();
        for (int i = 0; i < N - 1; i++)
        {
            for (int j = i + 1; j < N; j++)
            {
                Map[nums[i] + nums[j]] = new Tuple(i, j);
            }
        }
        return Map;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 10, 20, 30, 40, 1, 2 };
    int n = arr.Length;
    int X = 91;
    Dictionary> Map = twoSum(arr, n);
      
    // Function call
    fourSum(X, arr, Map, n);
  }
}
 
// This code is contributed by divyeshrabadiya07

Javascript


输出
20,30,40,1

复杂度分析:

  • 时间复杂度: O(n^2)。
    需要嵌套遍历将所有对存储在哈希 Map 中。
  • 辅助空间: O(n^2)。
    所有 n*(n-1) 对都存储在哈希 Map 中,因此所需空间为 O(n^2),临时数组采用 O(n),因此空间为 O(n^2)。

?list=PLqM7alHXFySEQDk2MDfbwEdjd2svVJH9p

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