给定一个由N个整数组成的数组arr [] ,任务是计算绝对差至少为K的所有不相交的对。
注意:对(arr [i],arr [j])和(arr [j],arr [i])被视为同一对。
例子:
Input: arr[] = {1, 3, 3, 5}, K = 2
Output: 2
Explanation:
The following two pairs satisfy the necessary conditions:
- {arr[0], arr[1]} = (1, 3) whose absolute difference is |1 – 3| = 2
- {arr[2], arr[3]} = (3, 5) whose absolute difference is |3 – 5| = 2
Input: arr[] = {1, 2, 3, 4}, K = 3
Output: 1
Explanation:
The only pair satisfying the necessary conditions is {arr[0], arr[3]} = (1, 4), since |1 – 4| = 3.
天真的方法:最简单的方法是生成给定数组的所有可能对,并计算绝对差至少为K的那些对,并使用辅助数组Visited []来标记已经成对的元素配对的元素。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count distinct pairs
// with absolute difference atleast K
void countPairsWithDiffK(int arr[],
int N, int K)
{
// Track the element that
// have been paired
int vis[N];
memset(vis, 0, sizeof(vis));
// Stores count of distinct pairs
int count = 0;
// Pick all elements one by one
for (int i = 0; i < N; i++) {
// If already visited
if (vis[i] == 1)
continue;
for (int j = i + 1; j < N; j++) {
// If already visited
if (vis[j] == 1)
continue;
// If difference is at least K
if (abs(arr[i] - arr[j]) >= K) {
// Mark element as visited and
// increment the count
count++;
vis[i] = 1;
vis[j] = 1;
break;
}
}
}
// Print the final count
cout << count << ' ';
}
// Driver Code
int main()
{
// Given arr[]
int arr[] = { 1, 3, 3, 5 };
// Size of array
int N = sizeof(arr) / sizeof(arr[0]);
// Given difference K
int K = 2;
// Function Call
countPairsWithDiffK(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to count distinct pairs
// with absolute difference atleast K
static void countPairsWithDiffK(int arr[],
int N, int K)
{
// Track the element that
// have been paired
int []vis = new int[N];
Arrays.fill(vis, 0);
// Stores count of distinct pairs
int count = 0;
// Pick all elements one by one
for(int i = 0; i < N; i++)
{
// If already visited
if (vis[i] == 1)
continue;
for(int j = i + 1; j < N; j++)
{
// If already visited
if (vis[j] == 1)
continue;
// If difference is at least K
if (Math.abs(arr[i] - arr[j]) >= K)
{
// Mark element as visited and
// increment the count
count++;
vis[i] = 1;
vis[j] = 1;
break;
}
}
}
// Print the final count
System.out.print(count);
}
// Driver Code
public static void main(String args[])
{
// Given arr[]
int arr[] = { 1, 3, 3, 5 };
// Size of array
int N = arr.length;
// Given difference K
int K = 2;
// Function Call
countPairsWithDiffK(arr, N, K);
}
}
// This code is contributed by bgangwar59
Python3
# Python3 program for the above approach
# Function to count distinct pairs
# with absolute difference atleast K
def countPairsWithDiffK(arr, N, K):
# Track the element that
# have been paired
vis = [0] * N
# Stores count of distinct pairs
count = 0
# Pick all elements one by one
for i in range(N):
# If already visited
if (vis[i] == 1):
continue
for j in range(i + 1, N):
# If already visited
if (vis[j] == 1):
continue
# If difference is at least K
if (abs(arr[i] - arr[j]) >= K):
# Mark element as visited and
# increment the count
count += 1
vis[i] = 1
vis[j] = 1
break
# Print the final count
print(count)
# Driver Code
if __name__ == '__main__':
# Given arr[]
arr = [ 1, 3, 3, 5 ]
# Size of array
N = len(arr)
# Given difference K
K = 2
# Function Call
countPairsWithDiffK(arr, N, K)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
class GFG{
// Function to count distinct pairs
// with absolute difference atleast K
static void countPairsWithDiffK(int[] arr, int N,
int K)
{
// Track the element that
// have been paired
int[] vis = new int[N];
// Stores count of distinct pairs
int count = 0;
// Pick all elements one by one
for(int i = 0; i < N; i++)
{
// If already visited
if (vis[i] == 1)
continue;
for(int j = i + 1; j < N; j++)
{
// If already visited
if (vis[j] == 1)
continue;
// If difference is at least K
if (Math.Abs(arr[i] - arr[j]) >= K)
{
// Mark element as visited and
// increment the count
count++;
vis[i] = 1;
vis[j] = 1;
break;
}
}
}
// Print the final count
Console.Write(count);
}
// Driver Code
public static void Main()
{
// Given arr[]
int[] arr = { 1, 3, 3, 5 };
// Size of array
int N = arr.Length;
// Given difference K
int K = 2;
// Function Call
countPairsWithDiffK(arr, N, K);
}
}
// This code is contributed by chitranayal
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if it is possible to
// form M pairs with abs diff at least K
bool isValid(int arr[], int n, int m,
int d)
{
// Traverse the array over [0, M]
for (int i = 0; i < m; i++) {
// If valid index
if (abs(arr[n - m + i]
- arr[i])
< d) {
return 0;
}
}
// Return 1
return 1;
}
// Function to count distinct pairs
// with absolute difference atleasr K
int countPairs(int arr[], int N, int K)
{
// Stores the count of all
// possible pairs
int ans = 0;
// Initialize left and right
int left = 0, right = N / 2 + 1;
// Sort the array
sort(arr, arr + N);
// Perform Binary Search
while (left < right) {
// Find the value of mid
int mid = (left + right) / 2;
// Check valid index
if (isValid(arr, N, mid, K)) {
// Update ans
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
// Print the answer
cout << ans << ' ';
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 1, 3, 3, 5 };
// Given difference K
int K = 2;
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
countPairs(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if it is possible to
// form M pairs with abs diff at least K
static int isValid(int arr[], int n, int m,
int d)
{
// Traverse the array over [0, M]
for(int i = 0; i < m; i++)
{
// If valid index
if (Math.abs(arr[n - m + i] - arr[i]) < d)
{
return 0;
}
}
// Return 1
return 1;
}
// Function to count distinct pairs
// with absolute difference atleasr K
static void countPairs(int arr[], int N, int K)
{
// Stores the count of all
// possible pairs
int ans = 0;
// Initialize left and right
int left = 0, right = N / 2 + 1;
// Sort the array
Arrays.sort(arr);
// Perform Binary Search
while (left < right)
{
// Find the value of mid
int mid = (left + right) / 2;
// Check valid index
if (isValid(arr, N, mid, K) == 1)
{
// Update ans
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
// Print the answer
System.out.print(ans);
}
// Driver Code
public static void main(String args[])
{
// Given array arr[]
int arr[] = { 1, 3, 3, 5 };
// Given difference K
int K = 2;
// Size of the array
int N = arr.length;
// Function call
countPairs(arr, N, K);
}
}
// This code is contributed by bgangwar59
Python3
# Python3 program for the above approach
# Function to check if it is possible to
# form M pairs with abs diff at least K
def isValid(arr, n, m, d):
# Traverse the array over [0, M]
for i in range(m):
# If valid index
if (abs(arr[n - m + i] - arr[i]) < d):
return 0
# Return 1
return 1
# Function to count distinct pairs
# with absolute difference atleasr K
def countPairs(arr, N, K):
# Stores the count of all
# possible pairs
ans = 0
# Initialize left and right
left = 0
right = N // 2 + 1
# Sort the array
arr.sort(reverse = False)
# Perform Binary Search
while (left < right):
# Find the value of mid
mid = (left + right) // 2
# Check valid index
if (isValid(arr, N, mid, K)):
# Update ans
ans = mid
left = mid + 1
else:
right = mid - 1
# Print the answer
print(ans, end = "")
# Driver Code
if __name__ == '__main__':
# Given array arr[]
arr = [ 1, 3, 3, 5 ]
# Given difference K
K = 2
# Size of the array
N = len(arr)
# Function call
countPairs(arr, N, K)
# This code is contributed by bgangwar59
C#
// C# program for the
// above approach
using System;
class GFG{
// Function to check if it
// is possible to form M
// pairs with abs diff at
// least K
static int isValid(int []arr, int n,
int m, int d)
{
// Traverse the array over
// [0, M]
for(int i = 0; i < m; i++)
{
// If valid index
if (Math.Abs(arr[n - m + i] -
arr[i]) < d)
{
return 0;
}
}
// Return 1
return 1;
}
// Function to count distinct
// pairs with absolute difference
// atleast K
static void countPairs(int []arr,
int N, int K)
{
// Stores the count of all
// possible pairs
int ans = 0;
// Initialize left
// and right
int left = 0,
right = N / 2 + 1;
// Sort the array
Array.Sort(arr);
// Perform Binary Search
while (left < right)
{
// Find the value of mid
int mid = (left +
right) / 2;
// Check valid index
if (isValid(arr, N,
mid, K) == 1)
{
// Update ans
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
// Print the answer
Console.WriteLine(ans);
}
// Driver Code
public static void Main()
{
// Given array arr[]
int []arr = {1, 3, 3, 5};
// Given difference K
int K = 2;
// Size of the array
int N = arr.Length;
// Function call
countPairs(arr, N, K);
}
}
// This code is contributed by surendra_gangwar
输出
2
时间复杂度: O(N 2 )
辅助空间: O(N)
高效的方法:高效的想法是使用二进制搜索来找到差异至少为K的第一次出现。步骤如下:
- 将给定数组按升序排序。
- 初始化cnt为0 ,它将存储所有可能的对的计数。
- 按照以下步骤执行二进制搜索:
- 将左初始化为0 ,将右初始化为N / 2 +1 。
- 找到mid的值((左+右)/ 2) 。
- 检查是否可以通过将最左边的M个元素与最右边的M个元素配对来形成中间数对,即检查arr [0] – arr [N – M]≥d,arr [1] – arr [N -M + 1]≥ d,…,arr [M – 1] – arr [N – 1]≥d 。
- 在上述步骤中,遍历数组[0,M] ,如果存在abs(arr [N – M + i]-arr [i])小于K的索引,则将其更新为(mid – 1) 。
- 否则,将left更新为mid +1和cnt更新为mid 。
- 完成上述步骤后,将cnt的值打印为所有可能的对数。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if it is possible to
// form M pairs with abs diff at least K
bool isValid(int arr[], int n, int m,
int d)
{
// Traverse the array over [0, M]
for (int i = 0; i < m; i++) {
// If valid index
if (abs(arr[n - m + i]
- arr[i])
< d) {
return 0;
}
}
// Return 1
return 1;
}
// Function to count distinct pairs
// with absolute difference atleasr K
int countPairs(int arr[], int N, int K)
{
// Stores the count of all
// possible pairs
int ans = 0;
// Initialize left and right
int left = 0, right = N / 2 + 1;
// Sort the array
sort(arr, arr + N);
// Perform Binary Search
while (left < right) {
// Find the value of mid
int mid = (left + right) / 2;
// Check valid index
if (isValid(arr, N, mid, K)) {
// Update ans
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
// Print the answer
cout << ans << ' ';
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 1, 3, 3, 5 };
// Given difference K
int K = 2;
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
countPairs(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if it is possible to
// form M pairs with abs diff at least K
static int isValid(int arr[], int n, int m,
int d)
{
// Traverse the array over [0, M]
for(int i = 0; i < m; i++)
{
// If valid index
if (Math.abs(arr[n - m + i] - arr[i]) < d)
{
return 0;
}
}
// Return 1
return 1;
}
// Function to count distinct pairs
// with absolute difference atleasr K
static void countPairs(int arr[], int N, int K)
{
// Stores the count of all
// possible pairs
int ans = 0;
// Initialize left and right
int left = 0, right = N / 2 + 1;
// Sort the array
Arrays.sort(arr);
// Perform Binary Search
while (left < right)
{
// Find the value of mid
int mid = (left + right) / 2;
// Check valid index
if (isValid(arr, N, mid, K) == 1)
{
// Update ans
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
// Print the answer
System.out.print(ans);
}
// Driver Code
public static void main(String args[])
{
// Given array arr[]
int arr[] = { 1, 3, 3, 5 };
// Given difference K
int K = 2;
// Size of the array
int N = arr.length;
// Function call
countPairs(arr, N, K);
}
}
// This code is contributed by bgangwar59
Python3
# Python3 program for the above approach
# Function to check if it is possible to
# form M pairs with abs diff at least K
def isValid(arr, n, m, d):
# Traverse the array over [0, M]
for i in range(m):
# If valid index
if (abs(arr[n - m + i] - arr[i]) < d):
return 0
# Return 1
return 1
# Function to count distinct pairs
# with absolute difference atleasr K
def countPairs(arr, N, K):
# Stores the count of all
# possible pairs
ans = 0
# Initialize left and right
left = 0
right = N // 2 + 1
# Sort the array
arr.sort(reverse = False)
# Perform Binary Search
while (left < right):
# Find the value of mid
mid = (left + right) // 2
# Check valid index
if (isValid(arr, N, mid, K)):
# Update ans
ans = mid
left = mid + 1
else:
right = mid - 1
# Print the answer
print(ans, end = "")
# Driver Code
if __name__ == '__main__':
# Given array arr[]
arr = [ 1, 3, 3, 5 ]
# Given difference K
K = 2
# Size of the array
N = len(arr)
# Function call
countPairs(arr, N, K)
# This code is contributed by bgangwar59
C#
// C# program for the
// above approach
using System;
class GFG{
// Function to check if it
// is possible to form M
// pairs with abs diff at
// least K
static int isValid(int []arr, int n,
int m, int d)
{
// Traverse the array over
// [0, M]
for(int i = 0; i < m; i++)
{
// If valid index
if (Math.Abs(arr[n - m + i] -
arr[i]) < d)
{
return 0;
}
}
// Return 1
return 1;
}
// Function to count distinct
// pairs with absolute difference
// atleast K
static void countPairs(int []arr,
int N, int K)
{
// Stores the count of all
// possible pairs
int ans = 0;
// Initialize left
// and right
int left = 0,
right = N / 2 + 1;
// Sort the array
Array.Sort(arr);
// Perform Binary Search
while (left < right)
{
// Find the value of mid
int mid = (left +
right) / 2;
// Check valid index
if (isValid(arr, N,
mid, K) == 1)
{
// Update ans
ans = mid;
left = mid + 1;
}
else
right = mid - 1;
}
// Print the answer
Console.WriteLine(ans);
}
// Driver Code
public static void Main()
{
// Given array arr[]
int []arr = {1, 3, 3, 5};
// Given difference K
int K = 2;
// Size of the array
int N = arr.Length;
// Function call
countPairs(arr, N, K);
}
}
// This code is contributed by surendra_gangwar
输出
2
时间复杂度: O(N * log N)
辅助空间: O(1)