给定一个整数数组arr [] ,任务是计算arr中有效的元素对数。一对(arr [x],arr [y])被认为是无效的,如果
- arr [x]
- abs(arr [x] – arr [y])是奇数
注意:对(ARR [X],ARR [Y])和(ARR [Y],ARR [X])是两个不同的双当x = y和改编[I]的所有可能值的值的i是! ≤120 。
例子:
Input: arr[] = {16, 17, 18}
Output: 2
Only valid pair is (18, 16)
Input: arr[] = {16, 16}
Output: 2
Valid pairs are (16, 16) and (16, 16)
方法:代替处理所有元素,我们可以处理代表数组中元素arr [i]计数的(arr [i],count)对。由于只有120个可能的值,因此我们对每个元素组进行频率计数,从而降低了总体复杂度。
对于每对(arr [x],countX)和(arr [y],countY) ,如果满足条件,则总有效对将为countX * countY 。
如果arr [x] = arr [y] ,则我们多计算了一些。在这种情况下,有效对将为countA *(countA – 1),因为没有元素可以与自身成对。
下面是上述方法的实现:
C++
//C++ implementation of the approach
#include
using namespace std;
// Function to return total valid pairs
int ValidPairs(int arr[],int n)
{
// Initialize count of all the elements
int count[121]={0};
// frequency count of all the elements
for(int i=0;i
Java
//Java implementation of the approach
class GFG{
// Function to return total valid pairs
static int ValidPairs(int arr[],int n)
{
// Initialize count of all the elements
int[] count=new int[121];
// frequency count of all the elements
for(int i=0;i
Python3
# Python3 implementation of the approach
# Function to return total valid pairs
def ValidPairs(arr):
# Initialize count of all the elements
count = [0] * 121
# frequency count of all the elements
for ele in arr:
count[ele] += 1
ans = 0
for eleX, countX in enumerate(count):
for eleY, countY in enumerate(count):
if eleX < eleY:
continue
if (abs(eleX - eleY) % 2 == 1):
continue
# Add total valid pairs
ans += countX * countY
if eleX == eleY:
# Exclude pairs made with a single element
# i.e. (x, x)
ans -= countX
return ans
# Driver Code
arr = [16, 17, 18]
# Function call to print required answer
print(ValidPairs(arr))
C#
//C# implementation of the approach
using System;
class GFG{
// Function to return total valid pairs
static int ValidPairs(int[] arr,int n)
{
// Initialize count of all the elements
int[] count=new int[121];
// frequency count of all the elements
for(int i=0;i
PHP
输出:
1