给定一个整数N和一个包含[1, N]范围内元素的数组arr[] ,任务是找到所有对(arr[i], arr[j])的计数,使得i < j和i == arr[j] 和 j == arr[i] 。
例子:
Input: N = 4, arr[] = {2, 1, 4, 3}
Output: 2
Explanation:
All possible pairs are {1, 2} and {3, 4}
Input: N = 5, arr[] = {5, 5, 5, 5, 1}
Output: 1
Explanation:
Only possible pair: {1, 5}
天真的方法:
最简单的方法是生成给定数组的所有可能对,如果任何对满足给定条件,则增加计数。最后,打印count的值。
时间复杂度: O(N 2 )
辅助空间: O(1)
有效的方法:
按照以下步骤解决上述方法:
- 遍历给定的数组并保留索引等于arr[arr[index] – 1] – 1的元素的计数(比如cnt )。这将计算具有给定标准的有效对。
- 遍历后,总计数由cnt/2给出,因为我们在上述遍历中对每对计数了两次。
下面是上述方法的实现:
C++
// C++ program to implement
// the above approach
#include
using namespace std;
// Function to print the count of pair
void countPairs(int N, int arr[])
{
int count = 0;
// Iterate over all the
// elements of the array
for(int i = 0; i < N; i++)
{
if (i == arr[arr[i] - 1] - 1)
{
// Increment the count
count++;
}
}
// Print the result
cout << (count / 2) << endl;
}
// Driver Code
int main()
{
int arr[] = { 2, 1, 4, 3 };
int N = sizeof(arr)/sizeof(arr[0]);
countPairs(N, arr);
}
// This code is contributed by Amit Katiyar
Java
// Java Program to implement
// the above approach
import java.util.*;
class GFG {
// Function to print the count of pair
static void countPairs(int N, int[] arr)
{
int count = 0;
// Iterate over all the
// elements of the array
for (int i = 0; i < N; i++) {
if (i == arr[arr[i] - 1] - 1) {
// Increment the count
count++;
}
}
// Print the result
System.out.println(count / 2);
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 2, 1, 4, 3 };
int N = arr.length;
countPairs(N, arr);
}
}
Python3
# Python3 program to implement
# the above approach
# Function to print the count of pair
def countPairs(N, arr):
count = 0
# Iterate over all the
# elements of the array
for i in range(N):
if (i == arr[arr[i] - 1] - 1):
# Increment the count
count += 1
# Print the result
print(count // 2)
# Driver Code
if __name__ == "__main__":
arr = [2, 1, 4, 3]
N = len(arr)
countPairs(N, arr)
# This code is contributed by Chitranayal
C#
// C# Program to implement
// the above approach
using System;
class GFG{
// Function to print the count of pair
static void countPairs(int N, int[] arr)
{
int count = 0;
// Iterate over all the
// elements of the array
for (int i = 0; i < N; i++)
{
if (i == arr[arr[i] - 1] - 1)
{
// Increment the count
count++;
}
}
// Print the result
Console.Write(count / 2);
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 2, 1, 4, 3 };
int N = arr.Length;
countPairs(N, arr);
}
}
// This code is contributed by Ritik Bansal
Javascript
输出:
2
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live