给定一个包含N 个元素的数组arr[] 。任务是计算索引(i, j)的总数,使得arr[i] != arr[j]和i < j 。
例子:
Input: arr[] = {1, 1, 2}
Output: 2
(1, 2) and (1, 2) are the only valid pairs.
Input: arr[] = {1, 2, 3}
Output: 3
Input: arr[] = {1, 1, 1}
Output: 0
方法:初始化一个计数变量cnt = 0并运行两个嵌套循环来检查每个可能的对当前对是否有效。如果有效,则增加计数变量。最后,打印有效对的计数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the
// count of valid pairs
int countPairs(int arr[], int n)
{
// To store the required count
int cnt = 0;
// For each index pair (i, j)
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
// If current pair is valid
// then increment the count
if (arr[i] != arr[j])
cnt++;
}
}
return cnt;
}
// Driven code
int main()
{
int arr[] = { 1, 1, 2 };
int n = sizeof(arr) / sizeof(int);
cout << countPairs(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the
// count of valid pairs
static int countPairs(int arr[], int n)
{
// To store the required count
int cnt = 0;
// For each index pair (i, j)
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
// If current pair is valid
// then increment the count
if (arr[i] != arr[j])
cnt++;
}
}
return cnt;
}
// Driven code
public static void main (String[] args)
{
int arr[] = { 1, 1, 2 };
int n = arr.length;
System.out.println(countPairs(arr, n));
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to return the
# count of valid pairs
def countPairs(arr, n):
# To store the required count
cnt = 0;
# For each index pair (i, j)
for i in range(n):
for j in range(i + 1, n):
# If current pair is valid
# then increment the count
if (arr[i] != arr[j]):
cnt += 1;
return cnt;
# Driver code
if __name__ == '__main__':
arr = [ 1, 1, 2 ];
n = len(arr);
print(countPairs(arr, n));
# This code is contributed by 29AjayKumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the
// count of valid pairs
static int countPairs(int []arr, int n)
{
// To store the required count
int cnt = 0;
// For each index pair (i, j)
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
// If current pair is valid
// then increment the count
if (arr[i] != arr[j])
cnt++;
}
}
return cnt;
}
// Driven code
public static void Main()
{
int []arr = { 1, 1, 2 };
int n = arr.Length;
Console.WriteLine(countPairs(arr, n));
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
2
时间复杂度: O(N 2 )
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live