给定一个大小为N的数组arr[]和一个整数K ,任务是找到数组中总和等于K的不同对的计数。
例子:
Input: arr[] = { 5, 6, 5, 7, 7, 8 }, K = 13
Output: 2
Explanation:
Pairs with sum K( = 13) are { (arr[0], arr[5]), (arr[1], arr[3]), (arr[1], arr[4]) }, i.e. {(5, 8), (6, 7), (6, 7)}.
Therefore, distinct pairs with sum K( = 13) are { (arr[0], arr[5]), (arr[1], arr[3]) }.
Therefore, the required output is 2.
Input: arr[] = { 2, 6, 7, 1, 8, 3 }, K = 10
Output : 2
Explanation:
Distinct pairs with sum K( = 13) are { (arr[0], arr[4]), (arr[2], arr[5]) }.
Therefore, the required output is 2.
朴素的方法:解决这个问题的最简单的方法是使用双指针技术。这个想法是对数组进行排序并从给定数组中删除所有连续的重复元素。最后,计算给定数组中总和等于 K 的对,按照以下步骤解决问题:
- 初始化一个变量,比如cntPairs ,以存储具有总和K的数组的不同对的计数。
- 按升序对数组进行排序。
- 初始化两个变量,比如i = 0 , j = N – 1作为左右指针的索引来遍历数组。
- 遍历数组并检查以下条件:
- 如果 arr[i] + arr[j] == K:删除连续重复的数组元素并将cntPairs增加1 。更新i = i + 1和j = j – 1 。
- 如果arr[i] + arr[j] < K则更新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 是否存在于地图中。如果发现为真,则将cntPairs增加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;
// 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
蟒蛇3
# 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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live