📜  计算给定总和的不重复对

📅  最后修改于: 2021-05-17 16:04:26             🧑  作者: Mango

给定大小为N的数组arr []和整数K ,任务是在数组中求和等于K的不重复对的计数。

例子:

天真的方法:解决此问题的最简单方法是使用两指针技术。这个想法是对数组进行排序,并从给定数组中删除所有连续的重复元素。最后,计算给定数组中总和等于K的对。请按照以下步骤解决问题:

  • 初始化一个变量,例如cntPairs ,以存储总和为K的数组的不同对的计数。
  • 按升序对数组进行排序。
  • 初始化两个变量,例如i = 0j = N – 1作为遍历数组的左右指针的索引。
  • 遍历数组并检查以下条件:
    • 如果arr [i] + arr [j] == K:删除连续的重复数组元素,并将cntPairs增加1 。更新i = i + 1j = j – 1
    • 如果arr [i] + arr [j] 则更新i = i + 1
    • 否则,更新j = j – 1
  • 最后,打印cntPairs的值。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to count distinct pairs
// in array whose sum equal to K
int cntDisPairs(int arr[],
                int N, int K)
{
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Sort the array
    sort(arr, arr + N);
 
    // Stores index of
    // the left pointer
    int i = 0;
 
    // Stores index of
    // the right pointer
    int j = N - 1;
 
    // Calculate count of distinct
    // pairs whose sum equal to K
    while (i < j) {
 
        // If sum of current pair
        // is equal to K
        if (arr[i] + arr[j] == K) {
 
            // Remove consecutive duplicate
            // array elements
            while (i < j && arr[i] == arr[i + 1]) {
 
                // Update i
                i++;
            }
 
            // Remove consecutive duplicate
            // array elements
            while (i < j && arr[j] == arr[j - 1]) {
 
                // Update j
                j--;
            }
 
            // Update cntPairs
            cntPairs += 1;
 
            // Update i
            i++;
 
            // Update j
            j--;
        }
 
        // if sum of current pair
        // less than K
        else if (arr[i] + arr[j] < K) {
 
            // Update i
            i++;
        }
        else {
 
            // Update j
            j--;
        }
    }
    return cntPairs;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 13;
    cout << cntDisPairs(arr, N, K);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to count distinct pairs
// in array whose sum equal to K
static int cntDisPairs(int arr[],
                int N, int K)
{
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Sort the array
    Arrays.sort(arr);
 
    // Stores index of
    // the left pointer
    int i = 0;
 
    // Stores index of
    // the right pointer
    int j = N - 1;
 
    // Calculate count of distinct
    // pairs whose sum equal to K
    while (i < j) {
 
        // If sum of current pair
        // is equal to K
        if (arr[i] + arr[j] == K) {
 
            // Remove consecutive duplicate
            // array elements
            while (i < j && arr[i] == arr[i + 1]) {
 
                // Update i
                i++;
            }
 
            // Remove consecutive duplicate
            // array elements
            while (i < j && arr[j] == arr[j - 1]) {
 
                // Update j
                j--;
            }
 
            // Update cntPairs
            cntPairs += 1;
 
            // Update i
            i++;
 
            // Update j
            j--;
        }
 
        // if sum of current pair
        // less than K
        else if (arr[i] + arr[j] < K) {
 
            // Update i
            i++;
        }
        else {
 
            // Update j
            j--;
        }
    }
    return cntPairs;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int N = arr.length;
    int K = 13;
    System.out.print(cntDisPairs(arr, N, K));
}
 
   
// This code is contributed by 29AjayKumar


Python3
# Python3 program to implement
# the above approach
 
# Function to count distinct pairs
# in array whose sum equal to K
def cntDisPairs(arr, N, K):
     
    # Stores count of distinct pairs
    # whose sum equal to K
    cntPairs = 0
 
    # Sort the array
    arr = sorted(arr)
 
    # Stores index of
    # the left pointer
    i = 0
 
    # Stores index of
    # the right pointer
    j = N - 1
 
    # Calculate count of distinct
    # pairs whose sum equal to K
    while (i < j):
 
        # If sum of current pair
        # is equal to K
        if (arr[i] + arr[j] == K):
 
            # Remove consecutive duplicate
            # array elements
            while (i < j and arr[i] == arr[i + 1]):
 
                # Update i
                i += 1
 
            # Remove consecutive duplicate
            # array elements
            while (i < j and arr[j] == arr[j - 1]):
 
                # Update j
                j -= 1
 
            # Update cntPairs
            cntPairs += 1
 
            # Update i
            i += 1
 
            # Update j
            j -= 1
 
        # If sum of current pair
        # less than K
        elif (arr[i] + arr[j] < K):
 
            # Update i
            i += 1
        else:
 
            # Update j
            j -= 1
             
    return cntPairs
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 5, 6, 5, 7, 7, 8 ]
    N = len(arr)
    K = 13
     
    print(cntDisPairs(arr, N, K))
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to count distinct pairs
// in array whose sum equal to K
static int cntDisPairs(int []arr,
                       int N, int K)
{
     
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Sort the array
    Array.Sort(arr);
 
    // Stores index of
    // the left pointer
    int i = 0;
 
    // Stores index of
    // the right pointer
    int j = N - 1;
 
    // Calculate count of distinct
    // pairs whose sum equal to K
    while (i < j)
    {
         
        // If sum of current pair
        // is equal to K
        if (arr[i] + arr[j] == K)
        {
             
            // Remove consecutive duplicate
            // array elements
            while (i < j && arr[i] == arr[i + 1])
            {
                 
                // Update i
                i++;
            }
 
            // Remove consecutive duplicate
            // array elements
            while (i < j && arr[j] == arr[j - 1])
            {
                 
                // Update j
                j--;
            }
 
            // Update cntPairs
            cntPairs += 1;
 
            // Update i
            i++;
 
            // Update j
            j--;
        }
 
        // If sum of current pair
        // less than K
        else if (arr[i] + arr[j] < K)
        {
             
            // Update i
            i++;
        }
        else
        {
             
            // Update j
            j--;
        }
    }
    return cntPairs;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 5, 6, 5, 7, 7, 8 };
    int N = arr.Length;
    int K = 13;
     
    Console.WriteLine(cntDisPairs(arr, N, K));
}
}
   
// This code is contributed by jana_sayantan


Javascript


C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to count distinct pairs
// in array whose sum equal to K
int cntDisPairs(int arr[],
                int N, int K)
{
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Store frequency of each distinct
    // element of the array
    unordered_map cntFre;
 
    for (int i = 0; i < N; i++) {
 
        // Update frequency
        // of arr[i]
        cntFre[arr[i]]++;
    }
 
    // Traverse the map
    for (auto it : cntFre) {
 
        // Stores key value
        // of the map
        int i = it.first;
 
        // If i is the half of K
        if (2 * i == K) {
 
            // If frequency of i
            // greater than  1
            if (cntFre[i] > 1)
                cntPairs += 2;
        }
 
        else {
 
            if (cntFre[K - i]) {
 
                // Update cntPairs
                cntPairs += 1;
            }
        }
    }
 
    // Update cntPairs
    cntPairs = cntPairs / 2;
 
    return cntPairs;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 13;
    cout << cntDisPairs(arr, N, K);
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG
{
 
// Function to count distinct pairs
// in array whose sum equal to K
static int cntDisPairs(int arr[],
                int N, int K)
{
   
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Store frequency of each distinct
    // element of the array
    HashMap cntFre = new HashMap();
 
    for (int i = 0; i < N; i++)
    {
 
        // Update frequency
        // of arr[i]
        if(cntFre.containsKey(arr[i]))
            cntFre.put(arr[i], cntFre.get(arr[i]) + 1);
         
        else
            cntFre.put(arr[i], 1);
    }
 
    // Traverse the map
    for (Map.Entry it : cntFre.entrySet())
    {
 
        // Stores key value
        // of the map
        int i = it.getKey();
 
        // If i is the half of K
        if (2 * i == K)
        {
 
            // If frequency of i
            // greater than  1
            if (cntFre.get(i) > 1)
                cntPairs += 2;
        }
 
        else
        {
            if (cntFre.containsKey(K - i))
            {
 
                // Update cntPairs
                cntPairs += 1;
            }
        }
    }
 
    // Update cntPairs
    cntPairs = cntPairs / 2;
    return cntPairs;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int N = arr.length;
    int K = 13;
    System.out.print(cntDisPairs(arr, N, K));
}
}
 
// This code  is contributed by shikhasingrajput


Python3
# Python3 program to implement
# the above approach
 
# Function to count distinct pairs
# in array whose sum equal to K
def cntDisPairs(arr, N, K):
   
    # Stores count of distinct pairs
    # whose sum equal to K
    cntPairs = 0
 
    # Store frequency of each distinct
    # element of the array
    cntFre = {}
 
    for i in arr:
         
        # Update frequency
        # of arr[i]
        if i in cntFre:
            cntFre[i] += 1
        else:
            cntFre[i] = 1
 
    # Traverse the map
    for key, value in cntFre.items():
 
        # Stores key value
        # of the map
        i = key
 
        # If i is the half of K
        if (2 * i == K):
             
            # If frequency of i
            # greater than  1
            if (cntFre[i] > 1):
                cntPairs += 2
        else:
            if (cntFre[K - i]):
 
                # Update cntPairs
                cntPairs += 1
 
    # Update cntPairs
    cntPairs = cntPairs / 2
 
    return cntPairs
 
# Driver Code
arr = [ 5, 6, 5, 7, 7, 8 ]
N = len(arr)
K = 13
           
print(int(cntDisPairs(arr, N, K)))
 
# This code is contributed by Dharanendra L V


C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to count distinct pairs
  // in array whose sum equal to K
  static int cntDisPairs(int []arr,
                         int N, int K)
  {
 
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Store frequency of each distinct
    // element of the array
    Dictionary cntFre = new Dictionary();
 
    for (int i = 0; i < N; i++)
    {
 
      // Update frequency
      // of arr[i]
      if(cntFre.ContainsKey(arr[i]))
        cntFre[arr[i]] = cntFre[arr[i]] + 1;
 
      else
        cntFre.Add(arr[i], 1);
    }
 
    // Traverse the map
    foreach (KeyValuePair it in cntFre)
    {
 
      // Stores key value
      // of the map
      int i = it.Key;
 
      // If i is the half of K
      if (2 * i == K)
      {
 
        // If frequency of i
        // greater than  1
        if (cntFre[i] > 1)
          cntPairs += 2;
      }
 
      else
      {
        if (cntFre.ContainsKey(K - i))
        {
 
          // Update cntPairs
          cntPairs += 1;
        }
      }
    }
 
    // Update cntPairs
    cntPairs = cntPairs / 2;
    return cntPairs;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = { 5, 6, 5, 7, 7, 8 };
    int N = arr.Length;
    int K = 13;
    Console.Write(cntDisPairs(arr, N, K));
  }
}
 
// This code is contributed by 29AjayKumar


输出:
2

时间复杂度: O(N * log(N))
辅助空间: O(1)

高效的方法:可以使用散列来优化上述方法。请按照以下步骤解决问题:

  • 初始化一个变量,例如cntPairs ,以存储总和等于K的数组的不同对的计数。
  • 初始化一个映射,例如cntFre ,以存储数组中每个不同元素的频率。
  • 遍历数组并将其存储在地图中的每个不同元素的频率。
  • 使用地图的键值作为i遍历地图,并检查密钥K – i是否存在于地图中。如果确定为true,则将cntPairs1
  • 最后,打印cntPairs的值。

下面是上述方法的实现:

C++

// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to count distinct pairs
// in array whose sum equal to K
int cntDisPairs(int arr[],
                int N, int K)
{
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Store frequency of each distinct
    // element of the array
    unordered_map cntFre;
 
    for (int i = 0; i < N; i++) {
 
        // Update frequency
        // of arr[i]
        cntFre[arr[i]]++;
    }
 
    // Traverse the map
    for (auto it : cntFre) {
 
        // Stores key value
        // of the map
        int i = it.first;
 
        // If i is the half of K
        if (2 * i == K) {
 
            // If frequency of i
            // greater than  1
            if (cntFre[i] > 1)
                cntPairs += 2;
        }
 
        else {
 
            if (cntFre[K - i]) {
 
                // Update cntPairs
                cntPairs += 1;
            }
        }
    }
 
    // Update cntPairs
    cntPairs = cntPairs / 2;
 
    return cntPairs;
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 13;
    cout << cntDisPairs(arr, N, K);
}

Java

// Java program to implement
// the above approach
import java.util.*;
 
class GFG
{
 
// Function to count distinct pairs
// in array whose sum equal to K
static int cntDisPairs(int arr[],
                int N, int K)
{
   
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Store frequency of each distinct
    // element of the array
    HashMap cntFre = new HashMap();
 
    for (int i = 0; i < N; i++)
    {
 
        // Update frequency
        // of arr[i]
        if(cntFre.containsKey(arr[i]))
            cntFre.put(arr[i], cntFre.get(arr[i]) + 1);
         
        else
            cntFre.put(arr[i], 1);
    }
 
    // Traverse the map
    for (Map.Entry it : cntFre.entrySet())
    {
 
        // Stores key value
        // of the map
        int i = it.getKey();
 
        // If i is the half of K
        if (2 * i == K)
        {
 
            // If frequency of i
            // greater than  1
            if (cntFre.get(i) > 1)
                cntPairs += 2;
        }
 
        else
        {
            if (cntFre.containsKey(K - i))
            {
 
                // Update cntPairs
                cntPairs += 1;
            }
        }
    }
 
    // Update cntPairs
    cntPairs = cntPairs / 2;
    return cntPairs;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, 6, 5, 7, 7, 8 };
    int N = arr.length;
    int K = 13;
    System.out.print(cntDisPairs(arr, N, K));
}
}
 
// This code  is contributed by shikhasingrajput

Python3

# Python3 program to implement
# the above approach
 
# Function to count distinct pairs
# in array whose sum equal to K
def cntDisPairs(arr, N, K):
   
    # Stores count of distinct pairs
    # whose sum equal to K
    cntPairs = 0
 
    # Store frequency of each distinct
    # element of the array
    cntFre = {}
 
    for i in arr:
         
        # Update frequency
        # of arr[i]
        if i in cntFre:
            cntFre[i] += 1
        else:
            cntFre[i] = 1
 
    # Traverse the map
    for key, value in cntFre.items():
 
        # Stores key value
        # of the map
        i = key
 
        # If i is the half of K
        if (2 * i == K):
             
            # If frequency of i
            # greater than  1
            if (cntFre[i] > 1):
                cntPairs += 2
        else:
            if (cntFre[K - i]):
 
                # Update cntPairs
                cntPairs += 1
 
    # Update cntPairs
    cntPairs = cntPairs / 2
 
    return cntPairs
 
# Driver Code
arr = [ 5, 6, 5, 7, 7, 8 ]
N = len(arr)
K = 13
           
print(int(cntDisPairs(arr, N, K)))
 
# This code is contributed by Dharanendra L V

C#

// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to count distinct pairs
  // in array whose sum equal to K
  static int cntDisPairs(int []arr,
                         int N, int K)
  {
 
    // Stores count of distinct pairs
    // whose sum equal to K
    int cntPairs = 0;
 
    // Store frequency of each distinct
    // element of the array
    Dictionary cntFre = new Dictionary();
 
    for (int i = 0; i < N; i++)
    {
 
      // Update frequency
      // of arr[i]
      if(cntFre.ContainsKey(arr[i]))
        cntFre[arr[i]] = cntFre[arr[i]] + 1;
 
      else
        cntFre.Add(arr[i], 1);
    }
 
    // Traverse the map
    foreach (KeyValuePair it in cntFre)
    {
 
      // Stores key value
      // of the map
      int i = it.Key;
 
      // If i is the half of K
      if (2 * i == K)
      {
 
        // If frequency of i
        // greater than  1
        if (cntFre[i] > 1)
          cntPairs += 2;
      }
 
      else
      {
        if (cntFre.ContainsKey(K - i))
        {
 
          // Update cntPairs
          cntPairs += 1;
        }
      }
    }
 
    // Update cntPairs
    cntPairs = cntPairs / 2;
    return cntPairs;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = { 5, 6, 5, 7, 7, 8 };
    int N = arr.Length;
    int K = 13;
    Console.Write(cntDisPairs(arr, N, K));
  }
}
 
// This code is contributed by 29AjayKumar
输出:
2

时间复杂度: O(N)
辅助空间: O(N)