📌  相关文章
📜  给定一个数组A []和一个数字x,检查A []中的对,总和为x

📅  最后修改于: 2021-04-27 19:36:40             🧑  作者: Mango

编写一个程序,给定n个数字的数组A []和另一个数字x,确定S中是否存在两个元素的总和恰好是x。

例子:

Input: arr[] = {0, -1, 2, -3, 1}
        sum = -2
Output: -3, 1
If we calculate the sum of the output,
1 + (-3) = -2

Input: arr[] = {1, -2, 1, 0, 5}
       sum = 0
Output: -1
No valid pair exists.

方法1排序和两指针技术。

方法:解决此问题的棘手方法可以是使用两指针技术。但是对于使用两个指针技术,必须对数组进行排序。对数组进行排序后,就可以使用两个指针分别标记数组的开始和结束。如果该和比这两种元素总和,移位左指针增加要求的总和的值,并且如果该总和大于所要求的值较小,移位右指针减小值。让我们通过一个例子来理解这一点。

注意:如果给定总和超过一对,则此算法仅报告一个。可以很容易地对此进行扩展。

算法:

  1. hasArrayTwoCandidates(A [],ar_size,sum)
  2. 以非降序对数组进行排序。
  3. 初始化两个索引变量以找到候选者
    排序数组中的元素。
    1. 首先初始化到最左边的索引:l = 0
    2. 初始化第二个最右边的索引:r = ar_size-1
  4. 当l
  5. 如果(A [l] + A [r] ==和),则返回1
  6. 否则if(A [l] + A [r]
  7. 其他r–
  • 整个数组中没有候选者-返回0
  • C++
    // C++ program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
     
    #include 
    using namespace std;
     
    // Function to check if array has 2 elements
    // whose sum is equal to the given value
    bool hasArrayTwoCandidates(int A[], int arr_size,
                               int sum)
    {
        int l, r;
     
        /* Sort the elements */
        sort(A, A + arr_size);
     
        /* Now look for the two candidates in
           the sorted array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return 1;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return 0;
    }
     
    /* Driver program to test above function */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        // Function calling
        if (hasArrayTwoCandidates(A, arr_size, n))
            cout << "Array has two elements"
                    " with given sum";
        else
            cout << "Array doesn't have two"
                    " elements with given sum";
     
        return 0;
    }


    C
    // C program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
     
    #include 
    #define bool int
     
    void quickSort(int*, int, int);
     
    bool hasArrayTwoCandidates(
        int A[], int arr_size, int sum)
    {
        int l, r;
     
        /* Sort the elements */
        quickSort(A, 0, arr_size - 1);
     
        /* Now look for the two candidates in the sorted
           array*/
        l = 0;
        r = arr_size - 1;
        while (l < r) {
            if (A[l] + A[r] == sum)
                return 1;
            else if (A[l] + A[r] < sum)
                l++;
            else // A[i] + A[j] > sum
                r--;
        }
        return 0;
    }
     
    /* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
        PURPOSE */
    void exchange(int* a, int* b)
    {
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }
     
    int partition(int A[], int si, int ei)
    {
        int x = A[ei];
        int i = (si - 1);
        int j;
     
        for (j = si; j <= ei - 1; j++) {
            if (A[j] <= x) {
                i++;
                exchange(&A[i], &A[j]);
            }
        }
        exchange(&A[i + 1], &A[ei]);
        return (i + 1);
    }
     
    /* Implementation of Quick Sort
    A[] --> Array to be sorted
    si  --> Starting index
    ei  --> Ending index
    */
    void quickSort(int A[], int si, int ei)
    {
        int pi; /* Partitioning index */
        if (si < ei) {
            pi = partition(A, si, ei);
            quickSort(A, si, pi - 1);
            quickSort(A, pi + 1, ei);
        }
    }
     
    /* Driver program to test above function */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, -8 };
        int n = 16;
        int arr_size = 6;
     
        if (hasArrayTwoCandidates(A, arr_size, n))
            printf("Array has two elements with given sum");
        else
            printf("Array doesn't have two elements with given sum");
     
        getchar();
        return 0;
    }


    Java
    // Java program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
    import java.util.*;
     
    class GFG {
        // Function to check if array has 2 elements
        // whose sum is equal to the given value
        static boolean hasArrayTwoCandidates(
            int A[],
            int arr_size, int sum)
        {
            int l, r;
     
            /* Sort the elements */
            Arrays.sort(A);
     
            /* Now look for the two candidates
            in the sorted array*/
            l = 0;
            r = arr_size - 1;
            while (l < r) {
                if (A[l] + A[r] == sum)
                    return true;
                else if (A[l] + A[r] < sum)
                    l++;
                else // A[i] + A[j] > sum
                    r--;
            }
            return false;
        }
     
        // Driver code
        public static void main(String args[])
        {
            int A[] = { 1, 4, 45, 6, 10, -8 };
            int n = 16;
            int arr_size = A.length;
     
            // Function calling
            if (hasArrayTwoCandidates(A, arr_size, n))
                System.out.println("Array has two "
                                   + "elements with given sum");
            else
                System.out.println("Array doesn't have "
                                   + "two elements with given sum");
        }
    }


    Python
    # Python program to check for the sum
    # condition to be satisified
     
    def hasArrayTwoCandidates(A, arr_size, sum):
         
        # sort the array
        quickSort(A, 0, arr_size-1)
        l = 0
        r = arr_size-1
         
        # traverse the array for the two elements
        while l Array to be sorted
    # si  --> Starting index
    # ei  --> Ending index
    def quickSort(A, si, ei):
        if si < ei:
            pi = partition(A, si, ei)
            quickSort(A, si, pi-1)
            quickSort(A, pi + 1, ei)
     
    # Utility function for partitioning
    # the array(used in quick sort)
    def partition(A, si, ei):
        x = A[ei]
        i = (si-1)
        for j in range(si, ei):
            if A[j] <= x:
                i += 1
                 
                # This operation is used to swap
                # two variables is python
                A[i], A[j] = A[j], A[i]
     
            A[i + 1], A[ei] = A[ei], A[i + 1]
             
        return i + 1
         
     
    # Driver program to test the functions
    A = [1, 4, 45, 6, 10, -8]
    n = 16
    if (hasArrayTwoCandidates(A, len(A), n)):
        print("Array has two elements with the given sum")
    else:
        print("Array doesn't have two elements
                                      with the given sum")
     
    ## This code is contributed by __Devesh Agrawal__


    C#
    // C# program to check for pair
    // in A[] with sum as x
     
    using System;
     
    class GFG {
        static bool hasArrayTwoCandidates(int[] A,
                           int arr_size, int sum)
        {
            int l, r;
     
            /* Sort the elements */
            sort(A, 0, arr_size - 1);
     
            /* Now look for the two candidates
            in the sorted array*/
            l = 0;
            r = arr_size - 1;
            while (l < r) {
                if (A[l] + A[r] == sum)
                    return true;
                else if (A[l] + A[r] < sum)
                    l++;
                else // A[i] + A[j] > sum
                    r--;
            }
            return false;
        }
     
        /* Below functions are only to sort the
        array using QuickSort */
     
        /* This function takes last element as pivot,
        places the pivot element at its correct
        position in sorted array, and places all
        smaller (smaller than pivot) to left of
        pivot and all greater elements to right
        of pivot */
        static int partition(int[] arr, int low, int high)
        {
            int pivot = arr[high];
     
            // index of smaller element
            int i = (low - 1);
            for (int j = low; j <= high - 1; j++) {
                // If current element is smaller
                // than or equal to pivot
                if (arr[j] <= pivot) {
                    i++;
     
                    // swap arr[i] and arr[j]
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
     
            // swap arr[i+1] and arr[high] (or pivot)
            int temp1 = arr[i + 1];
            arr[i + 1] = arr[high];
            arr[high] = temp1;
     
            return i + 1;
        }
     
        /* The main function that
        implements QuickSort()
        arr[] --> Array to be sorted,
        low --> Starting index,
        high --> Ending index */
        static void sort(int[] arr, int low, int high)
        {
            if (low < high) {
                /* pi is partitioning index, arr[pi]
                is now at right place */
                int pi = partition(arr, low, high);
     
                // Recursively sort elements before
                // partition and after partition
                sort(arr, low, pi - 1);
                sort(arr, pi + 1, high);
            }
        }
     
        // Driver code
        public static void Main()
        {
            int[] A = { 1, 4, 45, 6, 10, -8 };
            int n = 16;
            int arr_size = 6;
     
            if (hasArrayTwoCandidates(A, arr_size, n))
                Console.Write("Array has two elements"
                              + " with given sum");
            else
                Console.Write("Array doesn't have "
                              + "two elements with given sum");
        }
    }
     
    // This code is contributed by Sam007


    PHP
     sum
                $r--;
        }
        return 0;
    }
     
    // Driver Code
    $A = array (1, 4, 45, 6, 10, -8);
    $n = 16;
    $arr_size = sizeof($A);
     
    // Function calling
    if(hasArrayTwoCandidates($A, $arr_size, $n))
        echo "Array has two elements " .
                       "with given sum";
    else
        echo "Array doesn't have two " .
              "elements with given sum";
         
    // This code is contributed by m_kit
    ?>


    Javascript


    C++
    // C++ program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
    #include 
     
    using namespace std;
     
    void printPairs(int arr[], int arr_size, int sum)
    {
        unordered_set s;
        for (int i = 0; i < arr_size; i++)
        {
            int temp = sum - arr[i];
     
            if (s.find(temp) != s.end())
                cout << "Pair with given sum "
                     << sum << " is (" << arr[i] << ","
                        << temp << ")" << endl;
     
            s.insert(arr[i]);
        }
    }
     
    /* Driver Code */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        // Function calling
        printPairs(A, arr_size, n);
     
        return 0;
    }


    C
    // C program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
     
    // Works only if range elements is limited
    #include 
    #define MAX 100000
     
    void printPairs(int arr[], int arr_size, int sum)
    {
        int i, temp;
     
        /*initialize hash set as 0*/
        bool s[MAX] = { 0 };
     
        for (i = 0; i < arr_size; i++)
        {
            temp = sum - arr[i];
            if (s[temp] == 1)
                printf(
                    "Pair with given sum %d is (%d, %d) n",
                    sum, arr[i], temp);
            s[arr[i]] = 1;
        }
    }
     
    /* Driver Code */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        printPairs(A, arr_size, n);
     
        getchar();
        return 0;
    }


    Java
    // Java implementation using Hashing
    import java.io.*;
    import java.util.HashSet;
     
    class PairSum {
        static void printpairs(int arr[], int sum)
        {
            HashSet s = new HashSet();
            for (int i = 0; i < arr.length; ++i)
            {
                int temp = sum - arr[i];
     
                // checking for condition
                if (s.contains(temp)) {
                    System.out.println(
                        "Pair with given sum "
                        + sum + " is (" + arr[i]
                        + ", " + temp + ")");
                }
                s.add(arr[i]);
            }
        }
     
        // Driver Code
        public static void main(String[] args)
        {
            int A[] = { 1, 4, 45, 6, 10, 8 };
            int n = 16;
            printpairs(A, n);
        }
    }
     
    // This article is contributed by Aakash Hasija


    Python
    # Python program to find if there are
    # two elements wtih given sum
     
    # function to check for the given sum
    # in the array
    def printPairs(arr, arr_size, sum):
         
        # Create an empty hash set
        s = set()
         
        for i in range(0, arr_size):
            temp = sum-arr[i]
            if (temp in s):
                print "Pair with given sum "+ str(sum) +
           " is (" + str(arr[i]) + ", " + str(temp) + ")"
            s.add(arr[i])
     
    # driver code
    A = [1, 4, 45, 6, 10, 8]
    n = 16
    printPairs(A, len(A), n)
     
    # This code is contributed by __Devesh Agrawal__


    C#
    // C# implementation using Hashing
    using System;
    using System.Collections.Generic;
     
    class GFG {
        static void printpairs(int[] arr,
                               int sum)
        {
            HashSet s = new HashSet();
            for (int i = 0; i < arr.Length; ++i)
            {
                int temp = sum - arr[i];
     
                // checking for condition
                if (s.Contains(temp)) {
                    Console.Write("Pair with given sum " +
               sum + " is (" + arr[i] + ", " + temp + ")");
                }
                s.Add(arr[i]);
            }
        }
     
        // Driver Code
        static void Main()
        {
            int[] A = new int[] { 1, 4, 45,
                                  6, 10, 8 };
            int n = 16;
            printpairs(A, n);
        }
    }
     
    // This code is contributed by
    // Manish Shaw(manishshaw1)


    C++
    // Code in cpp to tell if there
    // exists a pair in array whose
    // sum results in x.
    #include 
    using namespace std;
     
    // Funtion to print pairs
    void printPairs(int a[], int n, int x)
    {
          int i;
        int rem[x];
        for (i = 0; i < x; i++)
        {
           
            // initializing the rem
            // values with 0's.
            rem[i] = 0;
        }
        for (i = 0; i < n; i++)
        {
            if (a[i] < x)
            {
     
                // Perform the remainder
                // operation only if the
                // element is x, as numbers
                // greater than x can't
                // be used to get a sum x.
                // Updating the count of remainders.
                rem[a[i] % x]++;
            }
        }
       
        // Traversing the remainder list
        // from start to middle to
        // find pairs
        for (i = 1; i < x / 2; i++)
        {
            if (rem[i] > 0 && rem[x - i] > 0)
            {
               
                // The elements with remainders
                // i and x-i will
                // result to a sum of x.
                // Once we get two
                // elements which add up to x ,
                // we print x and
                // break.
                cout << "Yes"
                     << "\n";
                break;
            }
        }
       
        // Once we reach middle of
        // remainder array, we have to
        // do operations based on x.
        if (i >= x / 2)
        {
            if (x % 2 == 0)
            {
                if (rem[x / 2] > 1)
                {
                   
                    // if x is even and
                    // we have more than 1
                    // elements with remainder
                    // x/2, then we will
                    // have two distinct elements
                    // which add up
                    // to x. if we dont have
                    //more than 1
                    // element, print "No".
                    cout << "Yes"
                         << "\n";
                }
                else
                {
                    cout << "No"
                         << "\n";
                }
            }
            else
            {
               
                // When x is odd we continue
                // the same process
                // which we did in previous loop.
                if (rem[x / 2] > 0 &&
                      rem[x - x / 2] > 0)
                {
                    cout << "Yes"
                         << "\n";
                }
                else
                {
                    cout << "No"
                         << "\n";
                }
            }
        }
    }
     
    /* Driver Code */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        // Function calling
        printPairs(A, arr_size, n);
     
        return 0;
    }
    // This article is contributed by Sai Sanjana Gudla


    Java
    // Code in Java to tell if there
    // exists a pair in array whose
    // sum results in x.
    import java.util.*;
    class GFG{
     
    // Funtion to print pairs
    static void printPairs(int a[], int n, int x)
    {
      int i;
      int []rem = new int[x];
      for (i = 0; i < x; i++)
      {
     
        // initializing the rem
        // values with 0's.
        rem[i] = 0;
      }
      for (i = 0; i < n; i++)
      {
        if (a[i] < x)
        {
     
          // Perform the remainder
          // operation only if the
          // element is x, as numbers
          // greater than x can't
          // be used to get a sum x.
          // Updating the count of remainders.
          rem[a[i] % x]++;
        }
      }
     
      // Traversing the remainder list
      // from start to middle to
      // find pairs
      for (i = 1; i < x / 2; i++)
      {
        if (rem[i] > 0 && rem[x - i] > 0)
        {
     
          // The elements with remainders
          // i and x-i will
          // result to a sum of x.
          // Once we get two
          // elements which add up to x ,
          // we print x and
          // break.
          System.out.print("Yes"
                           + "\n");
          break;
        }
      }
     
      // Once we reach middle of
      // remainder array, we have to
      // do operations based on x.
      if (i >= x / 2)
      {
        if (x % 2 == 0)
        {
          if (rem[x / 2] > 1)
          {
     
            // if x is even and
            // we have more than 1
            // elements with remainder
            // x/2, then we will
            // have two distinct elements
            // which add up
            // to x. if we dont have
            //more than 1
            // element, print "No".
            System.out.print("Yes"
                             + "\n");
          }
          else
          {
            System.out.print("No"
                             + "\n");
          }
        }
        else
        {
     
          // When x is odd we continue
          // the same process
          // which we did in previous loop.
          if (rem[x / 2] > 0 &&
              rem[x - x / 2] > 0)
          {
            System.out.print("Yes"
                             + "\n");
          }
          else
          {
            System.out.print("No"
                             + "\n");
          }
        }
      }
    }
     
    /* Driver Code */
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.length;
     
        // Function calling
        printPairs(A, arr_size, n);
    }
    }
     
    // This code is contributed by aashish1995


    Python3
    # Code in Python3 to tell if there
    # exists a pair in array whose
    # sum results in x.
     
    # Funtion to print pairs
    def printPairs(a, n, x):
         
        rem = []
         
        for i in range(x):
     
            # Initializing the rem
            # values with 0's.
            rem.append(0)
     
        for i in range(n):
            if (a[i] < x):
     
                # Perform the remainder operation
                # only if the element is x, as
                # numbers greater than x can't
                # be used to get a sum x.Updating
                # the count of remainders.
                rem[a[i] % x] += 1
     
        # Traversing the remainder list from
        # start to middle to find pairs
        for i in range(1, x // 2):
            if (rem[i] > 0 and rem[x - i] > 0):
     
                # The elements with remainders
                # i and x-i will result to a
                # sum of x. Once we get two
                # elements which add up to x,
                # we print x and break.
                print("Yes")
                break
     
        # Once we reach middle of
        # remainder array, we have to
        # do operations based on x.
        if (i >= x // 2):
            if (x % 2 == 0):
                if (rem[x // 2] > 1):
     
                    # If x is even and we have more
                    # than 1 elements with remainder
                    # x/2, then we will have two
                    # distinct elements which add up
                    # to x. if we dont have than 1
                    # element, print "No".
                    print("Yes")
                else:
                    print("No")
            else:
     
                # When x is odd we continue
                # the same process which we
                # did in previous loop.
                if (rem[x // 2] > 0 and
                    rem[x - x // 2] > 0):
                    print("Yes")
                else:
                    print("No")
     
    # Driver Code
    A = [ 1, 4, 45, 6, 10, 8 ]
    n = 16
    arr_size = len(A)
     
    # Function calling
    printPairs(A, arr_size, n)
     
    # This code is contributed by subhammahato348


    C#
    // C# Code in C# to tell if there
    // exists a pair in array whose
    // sum results in x.
    using System;
    class GFG
    {
       
    // Funtion to print pairs
    static void printPairs(int []a, int n, int x)
    {
      int i;
      int []rem = new int[x];
      for (i = 0; i < x; i++)
      {
         
        // initializing the rem
        // values with 0's.
        rem[i] = 0;
      }
      for (i = 0; i < n; i++)
      {
        if (a[i] < x)
        {
     
          // Perform the remainder
          // operation only if the
          // element is x, as numbers
          // greater than x can't
          // be used to get a sum x.
          // Updating the count of remainders.
          rem[a[i] % x]++;
        }
      }
     
      // Traversing the remainder list
      // from start to middle to
      // find pairs
      for (i = 1; i < x / 2; i++)
      {
        if (rem[i] > 0 && rem[x - i] > 0)
        {
     
          // The elements with remainders
          // i and x-i will
          // result to a sum of x.
          // Once we get two
          // elements which add up to x ,
          // we print x and
          // break.
          Console.Write("Yes" + "\n");
          break;
        }
      }
     
      // Once we reach middle of
      // remainder array, we have to
      // do operations based on x.
      if (i >= x / 2)
      {
        if (x % 2 == 0)
        {
          if (rem[x / 2] > 1)
          {
     
            // if x is even and
            // we have more than 1
            // elements with remainder
            // x/2, then we will
            // have two distinct elements
            // which add up
            // to x. if we dont have
            //more than 1
            // element, print "No".
            Console.Write("Yes" + "\n");
          }
          else
          {
            Console.Write("No"
                             + "\n");
          }
        }
        else
        {
     
          // When x is odd we continue
          // the same process
          // which we did in previous loop.
          if (rem[x / 2] > 0 &&
              rem[x - x / 2] > 0)
          {
            Console.Write("Yes"
                             + "\n");
          }
          else
          {
            Console.WriteLine("No"
                             + "\n");
          }
        }
      }
    }
     
    /* Driver Code */
    public static void Main(string[] args)
    {
        int[] A = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.Length;
     
        // Function calling
        printPairs(A, arr_size, n);
    }
    }
     
    // This code is contributed by SoumikMondal


    Javascript


    输出:

    Array has two elements with the given sum

    复杂度分析:

    • 时间复杂度:取决于我们使用哪种排序算法。
      • 如果使用合并排序或堆排序,则在最坏的情况下使用(-)(nlogn)。
      • 如果使用快速排序,则在最坏的情况下为O(n ^ 2)。
    • 辅助空间:这也取决于排序算法。辅助空间对于合并排序为O(n),对于堆排序为O(1)。

    方法2散列。

    方法:使用散列技术可以有效地解决此问题。如果存在值target_sum-x ,则使用hash_map检查当前数组值x(let) ,将其添加到前者后将得到target_sum 。这可以在恒定的时间内完成。让我们看下面的例子。

    算法:

    1. 初始化一个空的哈希表s。
    2. 对A []中的每个元素A [i]执行以下操作
      1. 如果设置了s [x – A [i]],则打印该对(A [i],x – A [i])
      2. 将A [i]插入s。

    伪代码:

    unordered_set s
    for(i=0 to end)
      if(s.find(target_sum - arr[i]) == s.end)
        insert(arr[i] into s)
      else 
        print arr[i], target-arr[i]

    C++

    // C++ program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
    #include 
     
    using namespace std;
     
    void printPairs(int arr[], int arr_size, int sum)
    {
        unordered_set s;
        for (int i = 0; i < arr_size; i++)
        {
            int temp = sum - arr[i];
     
            if (s.find(temp) != s.end())
                cout << "Pair with given sum "
                     << sum << " is (" << arr[i] << ","
                        << temp << ")" << endl;
     
            s.insert(arr[i]);
        }
    }
     
    /* Driver Code */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        // Function calling
        printPairs(A, arr_size, n);
     
        return 0;
    }
    

    C

    // C program to check if given array
    // has 2 elements whose sum is equal
    // to the given value
     
    // Works only if range elements is limited
    #include 
    #define MAX 100000
     
    void printPairs(int arr[], int arr_size, int sum)
    {
        int i, temp;
     
        /*initialize hash set as 0*/
        bool s[MAX] = { 0 };
     
        for (i = 0; i < arr_size; i++)
        {
            temp = sum - arr[i];
            if (s[temp] == 1)
                printf(
                    "Pair with given sum %d is (%d, %d) n",
                    sum, arr[i], temp);
            s[arr[i]] = 1;
        }
    }
     
    /* Driver Code */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        printPairs(A, arr_size, n);
     
        getchar();
        return 0;
    }
    

    Java

    // Java implementation using Hashing
    import java.io.*;
    import java.util.HashSet;
     
    class PairSum {
        static void printpairs(int arr[], int sum)
        {
            HashSet s = new HashSet();
            for (int i = 0; i < arr.length; ++i)
            {
                int temp = sum - arr[i];
     
                // checking for condition
                if (s.contains(temp)) {
                    System.out.println(
                        "Pair with given sum "
                        + sum + " is (" + arr[i]
                        + ", " + temp + ")");
                }
                s.add(arr[i]);
            }
        }
     
        // Driver Code
        public static void main(String[] args)
        {
            int A[] = { 1, 4, 45, 6, 10, 8 };
            int n = 16;
            printpairs(A, n);
        }
    }
     
    // This article is contributed by Aakash Hasija
    

    Python

    # Python program to find if there are
    # two elements wtih given sum
     
    # function to check for the given sum
    # in the array
    def printPairs(arr, arr_size, sum):
         
        # Create an empty hash set
        s = set()
         
        for i in range(0, arr_size):
            temp = sum-arr[i]
            if (temp in s):
                print "Pair with given sum "+ str(sum) +
           " is (" + str(arr[i]) + ", " + str(temp) + ")"
            s.add(arr[i])
     
    # driver code
    A = [1, 4, 45, 6, 10, 8]
    n = 16
    printPairs(A, len(A), n)
     
    # This code is contributed by __Devesh Agrawal__
    

    C#

    // C# implementation using Hashing
    using System;
    using System.Collections.Generic;
     
    class GFG {
        static void printpairs(int[] arr,
                               int sum)
        {
            HashSet s = new HashSet();
            for (int i = 0; i < arr.Length; ++i)
            {
                int temp = sum - arr[i];
     
                // checking for condition
                if (s.Contains(temp)) {
                    Console.Write("Pair with given sum " +
               sum + " is (" + arr[i] + ", " + temp + ")");
                }
                s.Add(arr[i]);
            }
        }
     
        // Driver Code
        static void Main()
        {
            int[] A = new int[] { 1, 4, 45,
                                  6, 10, 8 };
            int n = 16;
            printpairs(A, n);
        }
    }
     
    // This code is contributed by
    // Manish Shaw(manishshaw1)
    

    输出:

    Pair with given sum 16 is (10, 6)

    复杂度分析:

    • 时间复杂度: O(n)。
      由于整个数组只需要遍历一次。
    • 辅助空间: O(n)。
      哈希映射已用于存储数组元素。

    注意:如果数字范围包含负数,则也可以正常工作。

    方法3使用小于x的元素的余数。

    方法:
    这个想法是对除以x的元素进行计数,即除以x(即0到x-1) ,每个元素分别分开。假设x为6 ,则小于6且余数总计为6的数字相加后得出的总和为6。例如,我们在数组中有2,4个元素,2%6 = 2和4%6 = 4,这些余数加起来得到6。这样,我们必须检查是否有余数(1,5)对,(2,4),(3,3)。如果我们有一个或多个元素的余数为1且一个或多个元素的余数为5,则肯定得到的总和为6。在这里,我们不考虑(0,6),因为结果对的元素应小于6当涉及到(3,3)时,我们必须检查是否有两个元素的余数为3,那么我们可以说“存在一个对,其和为x”。

    算法:

    1.创建一个大小为x的数组。

    2.将所有rem元素初始化为零。

    3.遍历给定的数组

    • 如果arr [i]小于x,请执行以下操作:
      • r = arr [i]%x用来获得余数。
      • rem [r] = rem [r] +1,即增加除以x时剩余r的元素的数量。

    4.现在,将rem数组从1遍历到x / 2。

    • 如果(rem [i]> 0且rem [xi]> 0),则打印“是”并退出循环。这意味着我们有一对在做时导致x的结果。

    5.现在,当我们在上面的循环中到达x / 2时

    • 如果x是偶数,为了得到一对,我们应该有两个元素,其余为x / 2。
      • 如果rem [x / 2]> 1,则打印“是”,否则打印“否”
    • 如果不满足x是奇数,它将与xx / 2分开。
      • 如果rem [x / 2]> 1和rem [xx / 2]> 1,则打印“是”,否则打印“否”;否则,打印“否”。

    上述算法的执行情况

    C++

    // Code in cpp to tell if there
    // exists a pair in array whose
    // sum results in x.
    #include 
    using namespace std;
     
    // Funtion to print pairs
    void printPairs(int a[], int n, int x)
    {
          int i;
        int rem[x];
        for (i = 0; i < x; i++)
        {
           
            // initializing the rem
            // values with 0's.
            rem[i] = 0;
        }
        for (i = 0; i < n; i++)
        {
            if (a[i] < x)
            {
     
                // Perform the remainder
                // operation only if the
                // element is x, as numbers
                // greater than x can't
                // be used to get a sum x.
                // Updating the count of remainders.
                rem[a[i] % x]++;
            }
        }
       
        // Traversing the remainder list
        // from start to middle to
        // find pairs
        for (i = 1; i < x / 2; i++)
        {
            if (rem[i] > 0 && rem[x - i] > 0)
            {
               
                // The elements with remainders
                // i and x-i will
                // result to a sum of x.
                // Once we get two
                // elements which add up to x ,
                // we print x and
                // break.
                cout << "Yes"
                     << "\n";
                break;
            }
        }
       
        // Once we reach middle of
        // remainder array, we have to
        // do operations based on x.
        if (i >= x / 2)
        {
            if (x % 2 == 0)
            {
                if (rem[x / 2] > 1)
                {
                   
                    // if x is even and
                    // we have more than 1
                    // elements with remainder
                    // x/2, then we will
                    // have two distinct elements
                    // which add up
                    // to x. if we dont have
                    //more than 1
                    // element, print "No".
                    cout << "Yes"
                         << "\n";
                }
                else
                {
                    cout << "No"
                         << "\n";
                }
            }
            else
            {
               
                // When x is odd we continue
                // the same process
                // which we did in previous loop.
                if (rem[x / 2] > 0 &&
                      rem[x - x / 2] > 0)
                {
                    cout << "Yes"
                         << "\n";
                }
                else
                {
                    cout << "No"
                         << "\n";
                }
            }
        }
    }
     
    /* Driver Code */
    int main()
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = sizeof(A) / sizeof(A[0]);
     
        // Function calling
        printPairs(A, arr_size, n);
     
        return 0;
    }
    // This article is contributed by Sai Sanjana Gudla
    

    Java

    // Code in Java to tell if there
    // exists a pair in array whose
    // sum results in x.
    import java.util.*;
    class GFG{
     
    // Funtion to print pairs
    static void printPairs(int a[], int n, int x)
    {
      int i;
      int []rem = new int[x];
      for (i = 0; i < x; i++)
      {
     
        // initializing the rem
        // values with 0's.
        rem[i] = 0;
      }
      for (i = 0; i < n; i++)
      {
        if (a[i] < x)
        {
     
          // Perform the remainder
          // operation only if the
          // element is x, as numbers
          // greater than x can't
          // be used to get a sum x.
          // Updating the count of remainders.
          rem[a[i] % x]++;
        }
      }
     
      // Traversing the remainder list
      // from start to middle to
      // find pairs
      for (i = 1; i < x / 2; i++)
      {
        if (rem[i] > 0 && rem[x - i] > 0)
        {
     
          // The elements with remainders
          // i and x-i will
          // result to a sum of x.
          // Once we get two
          // elements which add up to x ,
          // we print x and
          // break.
          System.out.print("Yes"
                           + "\n");
          break;
        }
      }
     
      // Once we reach middle of
      // remainder array, we have to
      // do operations based on x.
      if (i >= x / 2)
      {
        if (x % 2 == 0)
        {
          if (rem[x / 2] > 1)
          {
     
            // if x is even and
            // we have more than 1
            // elements with remainder
            // x/2, then we will
            // have two distinct elements
            // which add up
            // to x. if we dont have
            //more than 1
            // element, print "No".
            System.out.print("Yes"
                             + "\n");
          }
          else
          {
            System.out.print("No"
                             + "\n");
          }
        }
        else
        {
     
          // When x is odd we continue
          // the same process
          // which we did in previous loop.
          if (rem[x / 2] > 0 &&
              rem[x - x / 2] > 0)
          {
            System.out.print("Yes"
                             + "\n");
          }
          else
          {
            System.out.print("No"
                             + "\n");
          }
        }
      }
    }
     
    /* Driver Code */
    public static void main(String[] args)
    {
        int A[] = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.length;
     
        // Function calling
        printPairs(A, arr_size, n);
    }
    }
     
    // This code is contributed by aashish1995
    

    Python3

    # Code in Python3 to tell if there
    # exists a pair in array whose
    # sum results in x.
     
    # Funtion to print pairs
    def printPairs(a, n, x):
         
        rem = []
         
        for i in range(x):
     
            # Initializing the rem
            # values with 0's.
            rem.append(0)
     
        for i in range(n):
            if (a[i] < x):
     
                # Perform the remainder operation
                # only if the element is x, as
                # numbers greater than x can't
                # be used to get a sum x.Updating
                # the count of remainders.
                rem[a[i] % x] += 1
     
        # Traversing the remainder list from
        # start to middle to find pairs
        for i in range(1, x // 2):
            if (rem[i] > 0 and rem[x - i] > 0):
     
                # The elements with remainders
                # i and x-i will result to a
                # sum of x. Once we get two
                # elements which add up to x,
                # we print x and break.
                print("Yes")
                break
     
        # Once we reach middle of
        # remainder array, we have to
        # do operations based on x.
        if (i >= x // 2):
            if (x % 2 == 0):
                if (rem[x // 2] > 1):
     
                    # If x is even and we have more
                    # than 1 elements with remainder
                    # x/2, then we will have two
                    # distinct elements which add up
                    # to x. if we dont have than 1
                    # element, print "No".
                    print("Yes")
                else:
                    print("No")
            else:
     
                # When x is odd we continue
                # the same process which we
                # did in previous loop.
                if (rem[x // 2] > 0 and
                    rem[x - x // 2] > 0):
                    print("Yes")
                else:
                    print("No")
     
    # Driver Code
    A = [ 1, 4, 45, 6, 10, 8 ]
    n = 16
    arr_size = len(A)
     
    # Function calling
    printPairs(A, arr_size, n)
     
    # This code is contributed by subhammahato348
    

    C#

    // C# Code in C# to tell if there
    // exists a pair in array whose
    // sum results in x.
    using System;
    class GFG
    {
       
    // Funtion to print pairs
    static void printPairs(int []a, int n, int x)
    {
      int i;
      int []rem = new int[x];
      for (i = 0; i < x; i++)
      {
         
        // initializing the rem
        // values with 0's.
        rem[i] = 0;
      }
      for (i = 0; i < n; i++)
      {
        if (a[i] < x)
        {
     
          // Perform the remainder
          // operation only if the
          // element is x, as numbers
          // greater than x can't
          // be used to get a sum x.
          // Updating the count of remainders.
          rem[a[i] % x]++;
        }
      }
     
      // Traversing the remainder list
      // from start to middle to
      // find pairs
      for (i = 1; i < x / 2; i++)
      {
        if (rem[i] > 0 && rem[x - i] > 0)
        {
     
          // The elements with remainders
          // i and x-i will
          // result to a sum of x.
          // Once we get two
          // elements which add up to x ,
          // we print x and
          // break.
          Console.Write("Yes" + "\n");
          break;
        }
      }
     
      // Once we reach middle of
      // remainder array, we have to
      // do operations based on x.
      if (i >= x / 2)
      {
        if (x % 2 == 0)
        {
          if (rem[x / 2] > 1)
          {
     
            // if x is even and
            // we have more than 1
            // elements with remainder
            // x/2, then we will
            // have two distinct elements
            // which add up
            // to x. if we dont have
            //more than 1
            // element, print "No".
            Console.Write("Yes" + "\n");
          }
          else
          {
            Console.Write("No"
                             + "\n");
          }
        }
        else
        {
     
          // When x is odd we continue
          // the same process
          // which we did in previous loop.
          if (rem[x / 2] > 0 &&
              rem[x - x / 2] > 0)
          {
            Console.Write("Yes"
                             + "\n");
          }
          else
          {
            Console.WriteLine("No"
                             + "\n");
          }
        }
      }
    }
     
    /* Driver Code */
    public static void Main(string[] args)
    {
        int[] A = { 1, 4, 45, 6, 10, 8 };
        int n = 16;
        int arr_size = A.Length;
     
        // Function calling
        printPairs(A, arr_size, n);
    }
    }
     
    // This code is contributed by SoumikMondal
    

    Java脚本

    
    
    输出
    Yes

    时间复杂度: O(n + x)
    辅助空间: O(x)
    相关问题:

    • 给定两个未排序的数组,找到总和为x的所有对
    • 计算给定总和的对
    • 计算所有等于k的不同对