📌  相关文章
📜  打印给定总和的所有对

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

给定一个整数数组和一个数字“sum”,打印数组中总和等于“sum”的所有对。

Examples :
Input  :  arr[] = {1, 5, 7, -1, 5}, 
          sum = 6
Output : (1, 5) (7, -1) (1, 5)

Input  :  arr[] = {2, 5, 17, -1}, 
          sum = 7
Output :  (2, 5)

一个简单的解决方案是遍历每个元素并检查数组中是否还有另一个数字可以添加到它以求和。

C++
// C++ implementation of simple method to
// find print pairs with given sum.
#include 
using namespace std;
 
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
int printPairs(int arr[], int n, int sum)
{
    int count = 0; // Initialize result
 
    // Consider all possible pairs and check
    // their sums
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (arr[i] + arr[j] == sum)
                cout << "(" << arr[i] << ", "
                     << arr[j] << ")" << endl;
}
 
// Driver function to test the above function
int main()
{
    int arr[] = { 1, 5, 7, -1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 6;
    printPairs(arr, n, sum);
    return 0;
}


Java
// Java implementation of
// simple method to find
// print pairs with given sum.
 
class GFG {
 
    // Returns number of pairs
    // in arr[0..n-1] with sum
    // equal to 'sum'
    static void printPairs(int arr[],
                           int n, int sum)
    {
        // int count = 0;
 
        // Consider all possible pairs
        // and check their sums
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                if (arr[i] + arr[j] == sum)
                    System.out.println("(" + arr[i] + ", " + arr[j] + ")");
    }
 
    // Driver Code
    public static void main(String[] arg)
    {
        int arr[] = { 1, 5, 7, -1, 5 };
        int n = arr.length;
        int sum = 6;
        printPairs(arr, n, sum);
    }
}
 
// This code is contributed
// by Smitha


Python3
# Python 3 implementation
# of simple method to find
# print pairs with given sum.
 
# Returns number of pairs
# in arr[0..n-1] with sum
# equal to 'sum'
def printPairs(arr, n, sum):
 
    # count = 0
 
    # Consider all possible
    # pairs and check their sums
    for i in range(0, n ):
        for j in range(i + 1, n ):
            if (arr[i] + arr[j] == sum):
                print("(", arr[i],
                      ", ", arr[j],
                      ")", sep = "")
 
 
# Driver Code
arr = [1, 5, 7, -1, 5]
n = len(arr)
sum = 6
printPairs(arr, n, sum)
 
# This code is contributed
# by Smitha


C#
// C# implementation of simple
// method to find print pairs
// with given sum.
using System;
 
class GFG {
    // Returns number of pairs
    // in arr[0..n-1] with sum
    // equal to 'sum'
    static void printPairs(int[] arr,
                           int n, int sum)
    {
        // int count = 0;
 
        // Consider all possible pairs
        // and check their sums
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                if (arr[i] + arr[j] == sum)
                    Console.Write("(" + arr[i] + ", " + arr[j] + ")"
                                  + "\n");
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 1, 5, 7, -1, 5 };
        int n = arr.Length;
        int sum = 6;
        printPairs(arr, n, sum);
    }
}
 
// This code is contributed
// by Smitha


PHP


Javascript


C++
// C++ implementation of simple method to
// find count of pairs with given sum.
#include 
using namespace std;
 
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
void printPairs(int arr[], int n, int sum)
{
    // Store counts of all elements in map m
    unordered_map m;
 
    // Traverse through all elements
    for (int i = 0; i < n; i++) {
 
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
        if (m.find(rem) != m.end()) {
            int count = m[rem];
            for (int j = 0; j < count; j++)
                cout << "(" << rem << ", "
                     << arr[i] << ")" << endl;
        }
        m[arr[i]]++;
    }
}
 
// Driver function to test the above function
int main()
{
    int arr[] = { 1, 5, 7, -1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 6;
    printPairs(arr, n, sum);
    return 0;
}


Java
// Java implementation of simple method to
// find count of pairs with given sum.
import java.util.*;
 
class GFG{
 
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
static void printPairs(int arr[], int n,
                       int sum)
{
     
    // Store counts of all elements in map m
    HashMap mp = new HashMap();
 
    // Traverse through all elements
    for(int i = 0; i < n; i++)
    {
         
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
        if (mp.containsKey(rem))
        {
            int count = mp.get(rem);
             
            for(int j = 0; j < count; j++)
                System.out.print("(" + rem +
                                ", " + arr[i] +
                                 ")" + "\n");
        }
        if (mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 5, 7, -1, 5 };
    int n = arr.length;
    int sum = 6;
     
    printPairs(arr, n, sum);
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 implementation of simple method to
# find count of pairs with given sum.
 
# Returns number of pairs in arr[0..n-1]
# with sum equal to 'sum'
def printPairs(arr, n, sum):
     
    # Store counts of all elements
    # in a dictionary
    mydict = dict()
 
    # Traverse through all the elements
    for i in range(n):
         
        # Search if a pair can be
        # formed with arr[i]
        temp = sum - arr[i]
         
        if temp in mydict:
            count = mydict[temp]
            for j in range(count):
                print("(", temp, ", ", arr[i],
                      ")", sep = "", end = '\n')
                       
        if arr[i] in mydict:
            mydict[arr[i]] += 1
        else:
            mydict[arr[i]] = 1
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 1, 5, 7, -1, 5 ]
    n = len(arr)
    sum = 6
 
    printPairs(arr, n, sum)
 
# This code is contributed by MuskanKalra1


C#
// C# implementation of simple method to
// find count of pairs with given sum.
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
  
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
static void printPairs(int []arr, int n, int sum)
{
     
    // Store counts of all elements in map m
    Dictionary m = new Dictionary();
                                        
    // Traverse through all elements
    for(int i = 0; i < n; i++)
    {
         
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
         
        if (m.ContainsKey(rem))
        {
            int count = m[rem];
             
            for(int j = 0; j < count; j++)
            {
                Console.Write("(" + rem + ", " +
                           arr[i] + ")" + "\n");
            }
        }
         
        if (m.ContainsKey(arr[i]))
        {
            m[arr[i]]++;
        }
        else
        {
            m[arr[i]] = 1;
        }
    }
}
 
// Driver code
public static void Main(string[] args)
{
    int []arr = { 1, 5, 7, -1, 5 };
    int n = arr.Length;
    int sum = 6;
     
    printPairs(arr, n, sum);
}
}
 
// This code is contributed by rutvik_56


Javascript


C++
// C++ code to implement
// the above approach
#include
using namespace std;
 
void pairedElements(int arr[],
                    int sum, int n)
{
  int low = 0;
  int high = n - 1;
 
  while (low < high)
  {
    if (arr[low] + arr[high] == sum)
    {
      cout << "The pair is : (" <<
               arr[low] << ", " <<
               arr[high] << ")" << endl;
    }
    if (arr[low] + arr[high] > sum)
    {
      high--;
    }
    else
    {
      low++;
    }
  }
}
 
// Driver code
int  main()
{
  int arr[] = {2, 3, 4, -2,
               6, 8, 9, 11};
  int n = sizeof(arr) / sizeof(arr[0]);
  sort(arr, arr + n);
  pairedElements(arr, 6, n);
}
 
// This code is contributed by Rajput-Ji


Java
import java.util.Arrays;
 
/**
 * Created by sampat.
 */
public class SumOfPairs {
 
    public void pairedElements(int arr[], int sum)
    {
        int low = 0;
        int high = arr.length - 1;
 
        while (low < high) {
            if (arr[low] + arr[high] == sum) {
                System.out.println("The pair is : ("
                                   + arr[low] + ", " + arr[high] + ")");
            }
            if (arr[low] + arr[high] > sum) {
                high--;
            }
            else {
                low++;
            }
        }
    }
 
    public static void main(String[] args)
    {
        int arr[] = { 2, 3, 4, -2, 6, 8, 9, 11 };
        Arrays.sort(arr);
 
        SumOfPairs sp = new SumOfPairs();
        sp.pairedElements(arr, 6);
    }
}


Python3
# Python3 program for the
# above approach
def pairedElements(arr, sum):
   
    low = 0;
    high = len(arr) - 1;
 
    while (low < high):
        if (arr[low] +
            arr[high] == sum):
            print("The pair is : (", arr[low],
                  ", ", arr[high], ")");
        if (arr[low] + arr[high] > sum):
            high -= 1;
        else:
            low += 1;
 
# Driver code
if __name__ == '__main__':
   
    arr = [2, 3, 4, -2,
           6, 8, 9, 11];
    arr.sort();
    pairedElements(arr, 6);
 
# This code contributed by shikhasingrajput


C#
// C# program to find triplets in a given
// array whose sum is equal to given sum.
using System;
 
public class SumOfPairs
{
 
    public void pairedElements(int []arr, int sum)
    {
        int low = 0;
        int high = arr.Length - 1;
 
        while (low < high)
        {
            if (arr[low] + arr[high] == sum)
            {
                Console.WriteLine("The pair is : ("
                                + arr[low] + ", " + arr[high] + ")");
            }
            if (arr[low] + arr[high] > sum)
            {
                high--;
            }
            else
            {
                low++;
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = { 2, 3, 4, -2, 6, 8, 9, 11 };
        Array.Sort(arr);
 
        SumOfPairs sp = new SumOfPairs();
        sp.pairedElements(arr, 6);
    }
}
 
// This code is contributed by Princi Singh


Javascript


输出 :
(1, 5)
(1, 5)
(7, -1)

方法 2(使用散列)
我们创建一个空的哈希表。现在我们遍历数组并检查哈希表中的对。如果找到匹配元素,我们打印匹配元素出现次数对的次数。
请注意,此解决方案的时间复杂度的最坏情况是O(c + n) ,其中 c 是具有给定总和的对数。

C++

// C++ implementation of simple method to
// find count of pairs with given sum.
#include 
using namespace std;
 
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
void printPairs(int arr[], int n, int sum)
{
    // Store counts of all elements in map m
    unordered_map m;
 
    // Traverse through all elements
    for (int i = 0; i < n; i++) {
 
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
        if (m.find(rem) != m.end()) {
            int count = m[rem];
            for (int j = 0; j < count; j++)
                cout << "(" << rem << ", "
                     << arr[i] << ")" << endl;
        }
        m[arr[i]]++;
    }
}
 
// Driver function to test the above function
int main()
{
    int arr[] = { 1, 5, 7, -1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int sum = 6;
    printPairs(arr, n, sum);
    return 0;
}

Java

// Java implementation of simple method to
// find count of pairs with given sum.
import java.util.*;
 
class GFG{
 
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
static void printPairs(int arr[], int n,
                       int sum)
{
     
    // Store counts of all elements in map m
    HashMap mp = new HashMap();
 
    // Traverse through all elements
    for(int i = 0; i < n; i++)
    {
         
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
        if (mp.containsKey(rem))
        {
            int count = mp.get(rem);
             
            for(int j = 0; j < count; j++)
                System.out.print("(" + rem +
                                ", " + arr[i] +
                                 ")" + "\n");
        }
        if (mp.containsKey(arr[i]))
        {
            mp.put(arr[i], mp.get(arr[i]) + 1);
        }
        else
        {
            mp.put(arr[i], 1);
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 5, 7, -1, 5 };
    int n = arr.length;
    int sum = 6;
     
    printPairs(arr, n, sum);
}
}
 
// This code is contributed by Princi Singh

蟒蛇3

# Python3 implementation of simple method to
# find count of pairs with given sum.
 
# Returns number of pairs in arr[0..n-1]
# with sum equal to 'sum'
def printPairs(arr, n, sum):
     
    # Store counts of all elements
    # in a dictionary
    mydict = dict()
 
    # Traverse through all the elements
    for i in range(n):
         
        # Search if a pair can be
        # formed with arr[i]
        temp = sum - arr[i]
         
        if temp in mydict:
            count = mydict[temp]
            for j in range(count):
                print("(", temp, ", ", arr[i],
                      ")", sep = "", end = '\n')
                       
        if arr[i] in mydict:
            mydict[arr[i]] += 1
        else:
            mydict[arr[i]] = 1
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 1, 5, 7, -1, 5 ]
    n = len(arr)
    sum = 6
 
    printPairs(arr, n, sum)
 
# This code is contributed by MuskanKalra1

C#

// C# implementation of simple method to
// find count of pairs with given sum.
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG{
  
// Returns number of pairs in arr[0..n-1]
// with sum equal to 'sum'
static void printPairs(int []arr, int n, int sum)
{
     
    // Store counts of all elements in map m
    Dictionary m = new Dictionary();
                                        
    // Traverse through all elements
    for(int i = 0; i < n; i++)
    {
         
        // Search if a pair can be formed with
        // arr[i].
        int rem = sum - arr[i];
         
        if (m.ContainsKey(rem))
        {
            int count = m[rem];
             
            for(int j = 0; j < count; j++)
            {
                Console.Write("(" + rem + ", " +
                           arr[i] + ")" + "\n");
            }
        }
         
        if (m.ContainsKey(arr[i]))
        {
            m[arr[i]]++;
        }
        else
        {
            m[arr[i]] = 1;
        }
    }
}
 
// Driver code
public static void Main(string[] args)
{
    int []arr = { 1, 5, 7, -1, 5 };
    int n = arr.Length;
    int sum = 6;
     
    printPairs(arr, n, sum);
}
}
 
// This code is contributed by rutvik_56

Javascript


输出 :

(1, 5)
(7, -1)
(1, 5)

方法三
打印给定总和的所有对的另一种方法如下:

C++

// C++ code to implement
// the above approach
#include
using namespace std;
 
void pairedElements(int arr[],
                    int sum, int n)
{
  int low = 0;
  int high = n - 1;
 
  while (low < high)
  {
    if (arr[low] + arr[high] == sum)
    {
      cout << "The pair is : (" <<
               arr[low] << ", " <<
               arr[high] << ")" << endl;
    }
    if (arr[low] + arr[high] > sum)
    {
      high--;
    }
    else
    {
      low++;
    }
  }
}
 
// Driver code
int  main()
{
  int arr[] = {2, 3, 4, -2,
               6, 8, 9, 11};
  int n = sizeof(arr) / sizeof(arr[0]);
  sort(arr, arr + n);
  pairedElements(arr, 6, n);
}
 
// This code is contributed by Rajput-Ji

Java

import java.util.Arrays;
 
/**
 * Created by sampat.
 */
public class SumOfPairs {
 
    public void pairedElements(int arr[], int sum)
    {
        int low = 0;
        int high = arr.length - 1;
 
        while (low < high) {
            if (arr[low] + arr[high] == sum) {
                System.out.println("The pair is : ("
                                   + arr[low] + ", " + arr[high] + ")");
            }
            if (arr[low] + arr[high] > sum) {
                high--;
            }
            else {
                low++;
            }
        }
    }
 
    public static void main(String[] args)
    {
        int arr[] = { 2, 3, 4, -2, 6, 8, 9, 11 };
        Arrays.sort(arr);
 
        SumOfPairs sp = new SumOfPairs();
        sp.pairedElements(arr, 6);
    }
}

蟒蛇3

# Python3 program for the
# above approach
def pairedElements(arr, sum):
   
    low = 0;
    high = len(arr) - 1;
 
    while (low < high):
        if (arr[low] +
            arr[high] == sum):
            print("The pair is : (", arr[low],
                  ", ", arr[high], ")");
        if (arr[low] + arr[high] > sum):
            high -= 1;
        else:
            low += 1;
 
# Driver code
if __name__ == '__main__':
   
    arr = [2, 3, 4, -2,
           6, 8, 9, 11];
    arr.sort();
    pairedElements(arr, 6);
 
# This code contributed by shikhasingrajput

C#

// C# program to find triplets in a given
// array whose sum is equal to given sum.
using System;
 
public class SumOfPairs
{
 
    public void pairedElements(int []arr, int sum)
    {
        int low = 0;
        int high = arr.Length - 1;
 
        while (low < high)
        {
            if (arr[low] + arr[high] == sum)
            {
                Console.WriteLine("The pair is : ("
                                + arr[low] + ", " + arr[high] + ")");
            }
            if (arr[low] + arr[high] > sum)
            {
                high--;
            }
            else
            {
                low++;
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = { 2, 3, 4, -2, 6, 8, 9, 11 };
        Array.Sort(arr);
 
        SumOfPairs sp = new SumOfPairs();
        sp.pairedElements(arr, 6);
    }
}
 
// This code is contributed by Princi Singh

Javascript


输出 :
The pair is : (-2, 8)
The pair is : (2, 4)

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