📌  相关文章
📜  数组中具有相等元素的索引对的计数

📅  最后修改于: 2021-10-27 16:54:43             🧑  作者: Mango

给定一个包含n 个元素的数组。任务是计算索引 (i, j) 的总数,使得 arr[i] = arr[j] 和 i != j
例子 :

Input : arr[] = {1, 1, 2}
Output : 1
As arr[0] = arr[1], the pair of indices is (0, 1)

Input : arr[] = {1, 1, 1}
Output : 3
As arr[0] = arr[1], the pair of indices is (0, 1), 
(0, 2) and (1, 2)

Input : arr[] = {1, 2, 3}
Output : 0

方法一(蛮力):
对于每个索引 i,查找其后与 arr[i] 具有相同值的元素。下面是这个方法的实现:

C++
// C++ program to count of pairs with equal
// elements in an array.
#include
using namespace std;
 
// Return the number of pairs with equal
// values.
int countPairs(int arr[], int n)
{
    int ans = 0;
 
    // for each index i and j
    for (int i = 0; i < n; i++)
        for (int j = i+1; j < n; j++)
 
            // finding the index with same
            // value but different index.
            if (arr[i] == arr[j])
                ans++;
    return ans;
}
 
// Driven Program
int main()
{
    int arr[] = { 1, 1, 2 };
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << countPairs(arr, n) << endl;
    return 0;
}


Java
// Java program to count of pairs with equal
// elements in an array.
class GFG {
         
    // Return the number of pairs with equal
    // values.
    static int countPairs(int arr[], int n)
    {
        int ans = 0;
     
        // for each index i and j
        for (int i = 0; i < n; i++)
            for (int j = i+1; j < n; j++)
     
                // finding the index with same
                // value but different index.
                if (arr[i] == arr[j])
                    ans++;
        return ans;
    }
     
    //driver 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 Anant Agarwal.


Python3
# Python3 program to
# count of pairs with equal
# elements in an array.
 
# Return the number of
# pairs with equal values.
def countPairs(arr, n):
 
    ans = 0
 
    # for each index i and j
    for i in range(0 , n):
        for j in range(i + 1, n):
 
            # finding the index
            # with same value but
            # different index.
            if (arr[i] == arr[j]):
                ans += 1
    return ans
 
# Driven Code
arr = [1, 1, 2 ]
n = len(arr)
print(countPairs(arr, n))
 
# This code is contributed
# by Smitha


C#
// C# program to count of pairs with equal
// elements in an array.
using System;
 
class GFG {
         
    // Return the number of pairs with equal
    // values.
    static int countPairs(int []arr, int n)
    {
        int ans = 0;
     
        // for each index i and j
        for (int i = 0; i < n; i++)
            for (int j = i+1; j < n; j++)
     
                // finding the index with same
                // value but different index.
                if (arr[i] == arr[j])
                    ans++;
        return ans;
    }
     
    // Driver code
    public static void Main ()
    {
        int []arr = { 1, 1, 2 };
        int n = arr.Length;
         
        Console.WriteLine(countPairs(arr, n));
    }
}
 
// This code is contributed by anuj_67.


PHP


Javascript


C++
// C++ program to count of index pairs with
// equal elements in an array.
#include
using namespace std;
 
// Return the number of pairs with equal
// values.
int countPairs(int arr[], int n)
{
    unordered_map mp;
 
    // Finding frequency of each number.
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Calculating pairs of each value.
    int ans = 0;
    for (auto it=mp.begin(); it!=mp.end(); it++)
    {
        int count = it->second;
        ans += (count * (count - 1))/2;
    }
 
    return ans;
}
 
// Driven Program
int main()
{
    int arr[] = {1, 1, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << countPairs(arr, n) << endl;
    return 0;
}


Java
// Java program to count of index pairs with
// equal elements in an array.
import java.util.*;
 
class GFG {
 
    public static int countPairs(int arr[], int n)
    {
        //A method to return number of pairs with
        // equal values
         
        HashMap hm = new HashMap<>();
         
        // Finding frequency of each number.
        for(int i = 0; i < n; i++)
        {
        if(hm.containsKey(arr[i]))
            hm.put(arr[i],hm.get(arr[i]) + 1);
        else
            hm.put(arr[i], 1);
        }
        int ans=0;
         
        // Calculating count of pairs with equal values
        for(Map.Entry it : hm.entrySet())
        {
            int count = it.getValue();
            ans += (count * (count - 1)) / 2;
        }
        return ans;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = new int[]{1, 2, 3, 1};
        System.out.println(countPairs(arr,arr.length));
    }
}
 
// This Code is Contributed
// by Adarsh_Verma


Python3
# Python3 program to count of index pairs
# with equal elements in an array.
import math as mt
 
# Return the number of pairs with
# equal values.
def countPairs(arr, n):
 
    mp = dict()
 
    # Finding frequency of each number.
    for i in range(n):
        if arr[i] in mp.keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Calculating pairs of each value.
    ans = 0
    for it in mp:
        count = mp[it]
        ans += (count * (count - 1)) // 2
    return ans
 
# Driver Code
arr = [1, 1, 2]
n = len(arr)
print(countPairs(arr, n))
 
# This code is contributed by mohit kumar 29


C#
// C# program to count of index pairs with
// equal elements in an array.
using System;
using System.Collections.Generic;
 
class GFG
{
     
    // Return the number of pairs with
    // equal values.
    public static int countPairs(int []arr, int n)
    {
        // A method to return number of pairs
        // with equal values
        Dictionary hm = new Dictionary();
         
        // Finding frequency of each number.
        for(int i = 0; i < n; i++)
        {
            if(hm.ContainsKey(arr[i]))
            {
                int a = hm[arr[i]];
                hm.Remove(arr[i]);
                hm.Add(arr[i], a + 1);
            }
            else
                hm.Add(arr[i], 1);
        }
        int ans = 0;
         
        // Calculating count of pairs with
        // equal values
        foreach(var it in hm)
        {
            int count = it.Value;
            ans += (count * (count - 1)) / 2;
        }
        return ans;
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = new int[]{1, 2, 3, 1};
        Console.WriteLine(countPairs(arr,arr.Length));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出 :

1

时间复杂度:O(n 2 )
方法二(高效方法):
这个想法是计算每个数字的频率,然后找到元素相等的对的数量。假设,数字 x 在索引 i 1 , i 2 ,….,i k处出现 k 次。然后选择任意两个索引 i x和 i y ,它们将被视为 1 对。同样,i y和i x也可以成对。因此,选择n C 2是满足 arr[i] = arr[j] = x 的对数。
下面是这个方法的实现:

C++

// C++ program to count of index pairs with
// equal elements in an array.
#include
using namespace std;
 
// Return the number of pairs with equal
// values.
int countPairs(int arr[], int n)
{
    unordered_map mp;
 
    // Finding frequency of each number.
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Calculating pairs of each value.
    int ans = 0;
    for (auto it=mp.begin(); it!=mp.end(); it++)
    {
        int count = it->second;
        ans += (count * (count - 1))/2;
    }
 
    return ans;
}
 
// Driven Program
int main()
{
    int arr[] = {1, 1, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    cout << countPairs(arr, n) << endl;
    return 0;
}

Java

// Java program to count of index pairs with
// equal elements in an array.
import java.util.*;
 
class GFG {
 
    public static int countPairs(int arr[], int n)
    {
        //A method to return number of pairs with
        // equal values
         
        HashMap hm = new HashMap<>();
         
        // Finding frequency of each number.
        for(int i = 0; i < n; i++)
        {
        if(hm.containsKey(arr[i]))
            hm.put(arr[i],hm.get(arr[i]) + 1);
        else
            hm.put(arr[i], 1);
        }
        int ans=0;
         
        // Calculating count of pairs with equal values
        for(Map.Entry it : hm.entrySet())
        {
            int count = it.getValue();
            ans += (count * (count - 1)) / 2;
        }
        return ans;
    }
     
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = new int[]{1, 2, 3, 1};
        System.out.println(countPairs(arr,arr.length));
    }
}
 
// This Code is Contributed
// by Adarsh_Verma

蟒蛇3

# Python3 program to count of index pairs
# with equal elements in an array.
import math as mt
 
# Return the number of pairs with
# equal values.
def countPairs(arr, n):
 
    mp = dict()
 
    # Finding frequency of each number.
    for i in range(n):
        if arr[i] in mp.keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Calculating pairs of each value.
    ans = 0
    for it in mp:
        count = mp[it]
        ans += (count * (count - 1)) // 2
    return ans
 
# Driver Code
arr = [1, 1, 2]
n = len(arr)
print(countPairs(arr, n))
 
# This code is contributed by mohit kumar 29

C#

// C# program to count of index pairs with
// equal elements in an array.
using System;
using System.Collections.Generic;
 
class GFG
{
     
    // Return the number of pairs with
    // equal values.
    public static int countPairs(int []arr, int n)
    {
        // A method to return number of pairs
        // with equal values
        Dictionary hm = new Dictionary();
         
        // Finding frequency of each number.
        for(int i = 0; i < n; i++)
        {
            if(hm.ContainsKey(arr[i]))
            {
                int a = hm[arr[i]];
                hm.Remove(arr[i]);
                hm.Add(arr[i], a + 1);
            }
            else
                hm.Add(arr[i], 1);
        }
        int ans = 0;
         
        // Calculating count of pairs with
        // equal values
        foreach(var it in hm)
        {
            int count = it.Value;
            ans += (count * (count - 1)) / 2;
        }
        return ans;
    }
     
    // Driver code
    public static void Main()
    {
        int []arr = new int[]{1, 2, 3, 1};
        Console.WriteLine(countPairs(arr,arr.Length));
    }
}
 
// This code is contributed by 29AjayKumar

Javascript


输出 :

1

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程