给定一个包含N 个元素的数组arr[] 。任务是计算索引(i, j)的总数,使得arr[i] = arr[j]和i != j
例子:
Input: arr[]={1, 2, 1, 1}
Output: 3
Explanation:
In the array arr[0]=arr[2]=arr[3]
Valid Pairs are (0, 2), (0, 3) and (2, 3)
Input: arr[]={2, 2, 3, 2, 3}
Output: 4
Explanation:
In the array arr[0]=arr[1]=arr[3] and arr[2]=arr[4]
So Valid Pairs are (0, 1), (0, 3), (1, 3), (2, 4)
对于朴素和高效的方法,请参阅本文的前一篇文章。
更好的方法——使用两个指针:这个想法是对给定的数组和具有相同元素的索引的差异进行排序。以下是步骤:
- 对给定的数组进行排序。
- 初始化两个指针左和右分别为0和1。
- 现在直到 right 小于N ,执行以下操作:
- 如果元素索引 left 和 right 相同,则增加右指针并将左右指针的差值添加到最终计数中。
- 否则更新从左到右的值。
- 完成上述步骤后打印count的值。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function that counts the pair in
// the array arr[]
int countPairs(int arr[], int n)
{
int ans = 0;
// Sort the array
sort(arr, arr + n);
// Initialize two pointers
int left = 0, right = 1;
while (right < n) {
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 2, 2, 3, 2, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << countPairs(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function that counts the pair in
// the array arr[]
static int countPairs(int arr[], int n)
{
int ans = 0;
// Sort the array
Arrays.sort(arr);
// Initialize two pointers
int left = 0, right = 1;
while (right < n)
{
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 2, 2, 3, 2, 3 };
int N = arr.length;
// Function call
System.out.print(countPairs(arr, N));
}
}
// This code is contributed by Rohit_ranjan
Python3
# Python3 program for the above approach
# Function that counts the pair in
# the array arr[]
def countPairs(arr, n):
ans = 0
# Sort the array
arr.sort()
# Initialize two pointers
left = 0
right = 1;
while (right < n):
if (arr[left] == arr[right]):
# Add all valid pairs to answer
ans += right - left;
else:
left = right;
right += 1
# Return the answer
return ans
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [2, 2, 3, 2, 3]
N = len(arr)
# Function call
print (countPairs(arr, N))
# This code is contributed by Chitranayal
C#
// C# program for the above approach
using System;
class GFG{
// Function that counts the pair in
// the array []arr
static int countPairs(int []arr, int n)
{
int ans = 0;
// Sort the array
Array.Sort(arr);
// Initialize two pointers
int left = 0, right = 1;
while (right < n)
{
if (arr[left] == arr[right])
// Add all valid pairs to answer
ans += right - left;
else
left = right;
right++;
}
// Return the answer
return ans;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 2, 2, 3, 2, 3 };
int N = arr.Length;
// Function call
Console.Write(countPairs(arr, N));
}
}
// This code is contributed by sapnasingh4991
Javascript
C++
// C++ program for the above approach
#include
using namespace std;
// Function that count the pairs having
// same elements in the array arr[]
int countPairs(int arr[], int n)
{
int ans = 0;
// Hash map to keep track of
// occurences of elements
unordered_map count;
// Traverse the array arr[]
for (int i = 0; i < n; i++) {
// Check if occurence of arr[i] > 0
// add count[arr[i]] to answer
if (count[arr[i]] != 0)
ans += count[arr[i]];
// Increase count of arr[i]
count[arr[i]]++;
}
// Return the result
return ans;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 1, 2, 1, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << countPairs(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function that count the pairs having
// same elements in the array arr[]
static int countPairs(int arr[], int n)
{
int ans = 0;
// Hash map to keep track of
// occurences of elements
HashMap count = new HashMap<>();
// Traverse the array arr[]
for (int i = 0; i < n; i++)
{
// Check if occurence of arr[i] > 0
// add count[arr[i]] to answer
if(count.containsKey(arr[i]))
{
ans += count.get(arr[i]);
count.put(arr[i], count.get(arr[i]) + 1);
}
else
{
count.put(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 1, 2, 1, 1 };
int N = arr.length;
// Function call
System.out.print(countPairs(arr, N));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program for the above approach
# Function that count the pairs having
# same elements in the array arr[]
def countPairs(arr, n) :
ans = 0
# Hash map to keep track of
# occurences of elements
count = {}
# Traverse the array arr[]
for i in range(n) :
# Check if occurence of arr[i] > 0
# add count[arr[i]] to answer
if arr[i] in count :
ans += count[arr[i]]
# Increase count of arr[i]
if arr[i] in count :
count[arr[i]] += 1
else :
count[arr[i]] = 1
# Return the result
return ans
# Given array arr[]
arr = [ 1, 2, 1, 1 ]
N = len(arr)
# Function call
print(countPairs(arr, N))
# This code is contributed by divyesh072019
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function that count the pairs having
// same elements in the array []arr
static int countPairs(int []arr, int n)
{
int ans = 0;
// Hash map to keep track of
// occurences of elements
Dictionary count = new Dictionary();
// Traverse the array []arr
for (int i = 0; i < n; i++)
{
// Check if occurence of arr[i] > 0
// add count[arr[i]] to answer
if(count.ContainsKey(arr[i]))
{
ans += count[arr[i]];
count[arr[i]] = count[arr[i]] + 1;
}
else
{
count.Add(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 1, 2, 1, 1 };
int N = arr.Length;
// Function call
Console.Write(countPairs(arr, N));
}
}
// This code is contributed by PrinciRaj1992
输出:
4
时间复杂度: O(N*log N)
辅助空间: O(1)
高效方法——使用单次遍历:想法是使用哈希并更新频率大于 1 的每一对的计数。以下是步骤:
- 创建一个 unordered_map M来存储数组中每个元素的频率。
- 遍历给定的数组并不断更新M中每个元素的频率。
- 在上述步骤中更新频率时,如果任何元素的频率大于 0,则将该频率计入最终计数。
- 在上述步骤之后打印对的计数。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function that count the pairs having
// same elements in the array arr[]
int countPairs(int arr[], int n)
{
int ans = 0;
// Hash map to keep track of
// occurences of elements
unordered_map count;
// Traverse the array arr[]
for (int i = 0; i < n; i++) {
// Check if occurence of arr[i] > 0
// add count[arr[i]] to answer
if (count[arr[i]] != 0)
ans += count[arr[i]];
// Increase count of arr[i]
count[arr[i]]++;
}
// Return the result
return ans;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 1, 2, 1, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << countPairs(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function that count the pairs having
// same elements in the array arr[]
static int countPairs(int arr[], int n)
{
int ans = 0;
// Hash map to keep track of
// occurences of elements
HashMap count = new HashMap<>();
// Traverse the array arr[]
for (int i = 0; i < n; i++)
{
// Check if occurence of arr[i] > 0
// add count[arr[i]] to answer
if(count.containsKey(arr[i]))
{
ans += count.get(arr[i]);
count.put(arr[i], count.get(arr[i]) + 1);
}
else
{
count.put(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 1, 2, 1, 1 };
int N = arr.length;
// Function call
System.out.print(countPairs(arr, N));
}
}
// This code is contributed by PrinciRaj1992
蟒蛇3
# Python3 program for the above approach
# Function that count the pairs having
# same elements in the array arr[]
def countPairs(arr, n) :
ans = 0
# Hash map to keep track of
# occurences of elements
count = {}
# Traverse the array arr[]
for i in range(n) :
# Check if occurence of arr[i] > 0
# add count[arr[i]] to answer
if arr[i] in count :
ans += count[arr[i]]
# Increase count of arr[i]
if arr[i] in count :
count[arr[i]] += 1
else :
count[arr[i]] = 1
# Return the result
return ans
# Given array arr[]
arr = [ 1, 2, 1, 1 ]
N = len(arr)
# Function call
print(countPairs(arr, N))
# This code is contributed by divyesh072019
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function that count the pairs having
// same elements in the array []arr
static int countPairs(int []arr, int n)
{
int ans = 0;
// Hash map to keep track of
// occurences of elements
Dictionary count = new Dictionary();
// Traverse the array []arr
for (int i = 0; i < n; i++)
{
// Check if occurence of arr[i] > 0
// add count[arr[i]] to answer
if(count.ContainsKey(arr[i]))
{
ans += count[arr[i]];
count[arr[i]] = count[arr[i]] + 1;
}
else
{
count.Add(arr[i], 1);
}
}
// Return the result
return ans;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 1, 2, 1, 1 };
int N = arr.Length;
// Function call
Console.Write(countPairs(arr, N));
}
}
// This code is contributed by PrinciRaj1992
输出:
3
时间复杂度: O(N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live