📌  相关文章
📜  数组中{X,Y}对的计数,使得X⊕Y中设置位的计数与X&Y中设置位的计数的两倍之和为M

📅  最后修改于: 2021-05-17 04:45:47             🧑  作者: Mango

给定一个由n个非负整数和整数M组成的数组arr [] ,任务是查找满足条件setBits(X⊕Y)+ 2 * setBits的数组元素的无序对{X,Y}数量(X&Y)= M ,其中表示按位XOR, 表示按位AND。

例子:

天真的方法:最简单的方法是从给定的数组生成所有可能的对,并针对每个对检查是否满足必要条件。增加满足给定条件的对的计数,最后打印对的计数。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效的方法:可以基于以下观察来优化上述方法:

请按照以下步骤解决问题:

  • 首先,遍历数组arr []。
  • 对于每个数组元素arr [i],使用其中存在的设置位数对arr [i]进行更新
  • 现在从总和等于M的数组中打印对数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count number
// of setbits in the number n
int countsetbits(int n)
{
    // Stores the count of setbits
    int count = 0;
 
    // Iterate while N is
    // greater than 0
    while (n) {
 
        // Increment count by 1
        // if N is odd
        count += n & 1;
 
        // Right shift N
        n >>= 1;
    }
 
    // Return the count of set bits
    return (count);
}
 
// Function to find total count of
// given pairs satisfying the equation
int countPairs(int a[], int N, int M)
{
 
    for (int i = 0; i < N; i++) {
 
        // Update arr[i] with the count
        // of set bits of arr[i]
        a[i] = countsetbits(a[i]);
    }
 
    // Stores the frequency
    // of each array element
    unordered_map mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Increment the count
        // of arr[i] in mp
        mp[a[i]]++;
    }
 
    // Stores the total count of pairs
    int count = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Increment count by mp[M - a[i]]
        count += mp[M - a[i]];
 
        // If a[i] is equal to M-a[i]
        if (a[i] == M - a[i]) {
 
            // Decrment count by 1
            count--;
        }
    }
 
    // Return count/2
    return (count / 2);
}
 
// Driver Code
int main()
{
    // Input
    int arr[] = { 3, 0, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int M = 2;
 
    cout << countPairs(arr, N, M);
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to count number
// of setbits in the number n
static int countsetbits(int n)
{
     
    // Stores the count of setbits
    int count = 0;
 
    // Iterate while N is
    // greater than 0
    while (n != 0)
    {
         
        // Increment count by 1
        // if N is odd
        count += n & 1;
 
        // Right shift N
        n >>= 1;
    }
 
    // Return the count of set bits
    return (count);
}
 
// Function to find total count of
// given pairs satisfying the equation
static int countPairs(int[] a, int N, int M)
{
    for(int i = 0; i < N; i++)
    {
         
        // Update arr[i] with the count
        // of set bits of arr[i]
        a[i] = countsetbits(a[i]);
    }
 
    // Stores the frequency
    // of each array element
     HashMap mp = new HashMap();
 
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
        if (mp.containsKey(a[i]))
        {
            mp.put(a[i], mp.get(a[i]) + 1);
        }
        else
        {
            mp.put(a[i], 1);
        }
    }
     
    // Stores the total count of pairs
    int count = 0;
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Increment count by mp[M - a[i]]
        count += mp.get(M - a[i]);
 
        // If a[i] is equal to M-a[i]
        if (a[i] == M - a[i])
        {
             
            // Decrment count by 1
            count--;
        }
    }
 
    // Return count/2
    return (count / 2);
}   
 
// Driver Code
public static void main(String[] args)
{
     
    // Input
    int[] arr = { 3, 0, 4, 5 };
    int N = arr.length;
    int M = 2;
 
    System.out.println(countPairs(arr, N, M));
}
}
 
// This code is contributed by avijitmondal1998


Python3
# Python3 Program for the above approach
 
# Function to count number
# of setbits in the number n
def  countSetBits(n):
   
    # Stores the count of setbits
    count = 0
     
    # Iterate while N is
    # greater than 0
    while (n):
       
        # Increment count by 1
        # if N is odd
        count += n & 1
         
        # Right shift N
        n >>= 1
         
    # Return the count of set bits
    return count
 
def countPairs(arr, N, M):
    for i in range(0, N):
       
        # Update arr[i] with the count
        # of set bits of arr[i]
        arr[i] = countSetBits(arr[i])
         
    # Store counts of all elements in a dictionary
    mp = {}
    for i in range(0, N):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    twice_count = 0
     
    # Iterate through each element and increment
    # the count (Notice that every pair is
    # counted twice)
    for i in range(0, N):
        if M - arr[i] in mp.keys():
            twice_count += mp[M - arr[i]]
             
        # if (arr[i], arr[i]) pair satisfies the
        # condition, then we need to ensure that
        # the count is  decreased by one such
        # that the (arr[i], arr[i]) pair is not
        # considered
        if (M - arr[i] == arr[i]):
            twice_count -= 1
  
    # return the half of twice_count
    return int(twice_count / 2)
         
# Driver code
# Input
arr = [ 3, 0, 4, 5]
N = len(arr)
M = 2
print(countPairs(arr, N, M))
 
# This cose is contributed by santhoshcharan.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count number
// of setbits in the number n
static int countsetbits(int n)
{
     
    // Stores the count of setbits
    int count = 0;
 
    // Iterate while N is
    // greater than 0
    while (n != 0)
    {
         
        // Increment count by 1
        // if N is odd
        count += n & 1;
 
        // Right shift N
        n >>= 1;
    }
 
    // Return the count of set bits
    return (count);
}
 
// Function to find total count of
// given pairs satisfying the equation
static int countPairs(int[] a, int N, int M)
{
    for(int i = 0; i < N; i++)
    {
         
        // Update arr[i] with the count
        // of set bits of arr[i]
        a[i] = countsetbits(a[i]);
    }
 
    // Stores the frequency
    // of each array element
    Dictionary mp = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < N; ++i)
    {
            
        // Update frequency of
        // each array element
        if (mp.ContainsKey(a[i]) == true)
            mp[a[i]] += 1;
        else
            mp[a[i]] = 1;
    }
     
    // Stores the total count of pairs
    int count = 0;
 
    // Traverse the array arr[]
    for(int i = 0; i < N; i++)
    {
         
        // Increment count by mp[M - a[i]]
        count += mp[M - a[i]];
 
        // If a[i] is equal to M-a[i]
        if (a[i] == M - a[i])
        {
             
            // Decrment count by 1
            count--;
        }
    }
 
    // Return count/2
    return (count / 2);
}
 
// Driver Code
static public void Main()
{
     
    // Input
    int[] arr = { 3, 0, 4, 5 };
    int N = arr.Length;
    int M = 2;
 
    Console.WriteLine(countPairs(arr, N, M));
}
}
 
// This code is contributed by sanjoy_62


输出:
2

时间复杂度: O(N)
辅助空间: O(1)