📌  相关文章
📜  对数组中的对进行计数,以使两个元素都具有相等的设置位

📅  最后修改于: 2021-04-28 14:28:21             🧑  作者: Mango

给定具有唯一元素的数组arr ,任务是计算设置位计数相等的元素对的总数。

例子:

方法:

  • 从左到右遍历数组,并计算每个整数的设置位总数。
  • 使用映射来存储具有相同设置位数的元素的数量,其中设置位数作为键,并计数为值。
  • 然后迭代地图元素,并计算从n个元素(对于地图的每个元素)可以形成多少对两个元素,即(n *(n-1))/ 2
  • 最终结果将是地图上每个元素的上一步输出的总和。

以下是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
  
// Function to count all pairs
// with equal set bits count
int totalPairs(int arr[], int n)
{
    // map to store count of elements
    // with equal number of set bits
    map m;
    for (int i = 0; i < n; i++) {
  
        // inbuilt function that returns the
        // count of set bits of the number
        m[__builtin_popcount(arr[i])]++;
    }
  
    map::iterator it;
    int result = 0;
    for (it = m.begin(); it != m.end(); it++) {
  
        // there can be (n*(n-1)/2) unique two-
        // element pairs to choose from n elements
        result
            += (*it).second * ((*it).second - 1) / 2;
    }
  
    return result;
}
  
// Driver code
int main()
{
    int arr[] = { 7, 5, 3, 9, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << totalPairs(arr, n);
  
    return 0;
}


Java
import java.util.*;
  
class GFG {
      
    /* Function to get no of set  
    bits in binary representation  
    of passed binary no. */
    static int countSetBits(int n) 
    { 
        int count = 0; 
        while (n > 0) 
        { 
            n &= (n - 1) ; 
            count++; 
        } 
        return count; 
    } 
      
    // Function to count all pairs
    // with equal set bits count
    static int totalPairs(int arr[], int n)
    {
        // map to store count of elements
        // with equal number of set bits
        HashMap m = new HashMap<>();
        for (int i = 0; i < n; i++) {
      
            // function that returns the
            // count of set bits of the number
            int count = countSetBits(arr[i]);
            if(m.containsKey(count))
                m.put(count, m.get(count) + 1);
            else
                m.put(count, 1);
        }
      
        int result = 0;
        for (Map.Entry entry : m.entrySet()) {
            int value = entry.getValue();
              
            // there can be (n*(n-1)/2) unique two-
            // element pairs to choose from n elements
            result += ((value * (value -1)) / 2);
        }
      
        return result;
    }
      
    public static void main (String[] args) {
        int arr[] = { 7, 5, 3, 9, 1, 2 };
        int n = arr.length;
        System.out.println(totalPairs(arr, n));
    }
}


Python3
# Python3 implementation of the above approach
  
# Function to count all pairs
# with equal set bits count
def totalPairs(arr, n):
      
    # map to store count of elements
    # with equal number of set bits
    m = dict()
  
    for i in range(n):
  
        # inbuilt function that returns the
        # count of set bits of the number
        x = bin(arr[i]).count('1')
  
        m[x] = m.get(x, 0) + 1;
  
    result = 0
    for it in m:
  
        # there can be (n*(n-1)/2) unique two-
        # element pairs to choose from n elements
        result+= (m[it] * (m[it] - 1)) // 2
      
    return result
  
# Driver code
arr = [7, 5, 3, 9, 1, 2]
n = len(arr)
  
print(totalPairs(arr, n))
  
# This code is contributed by mohit kumar


C#
// C# program to rearrange a string so that all same 
// characters become atleast d distance away 
using System;
using System.Collections.Generic;
  
class GFG
{
      
    /* Function to get no of set 
    bits in binary representation 
    of passed binary no. */
    static int countSetBits(int n) 
    { 
        int count = 0; 
        while (n > 0) 
        { 
            n &= (n - 1) ; 
            count++; 
        } 
        return count; 
    } 
      
    // Function to count all pairs
    // with equal set bits count
    static int totalPairs(int []arr, int n)
    {
        // map to store count of elements
        // with equal number of set bits
        Dictionary mp = new Dictionary();
        for (int i = 0 ; i < n; i++)
        {
            // function that returns the
            // count of set bits of the number
            int count = countSetBits(arr[i]);
            if(mp.ContainsKey(count))
            {
                var val = mp[count];
                mp.Remove(count);
                mp.Add(count, val + 1); 
            }
            else
            {
                mp.Add(count, 1);
            }
        }
      
        int result = 0;
        foreach(KeyValuePair entry in mp){
            int values = entry.Value;
              
            // there can be (n*(n-1)/2) unique two-
            // element pairs to choose from n elements
            result += ((values * (values -1)) / 2);
        }
      
        return result;
    }
      
    // Driver code
    public static void Main (String[] args) 
    {
        int []arr = { 7, 5, 3, 9, 1, 2 };
        int n = arr.Length;
        Console.WriteLine(totalPairs(arr, n));
    }
}
  
// This code is contributed by Princi Singh


输出:
4