📌  相关文章
📜  计算来自其AND和XOR之和等于K的两倍的数组中的对

📅  最后修改于: 2021-05-18 00:26:21             🧑  作者: Mango

给定由N个整数和整数K组成的数组arr [] ,任务是计算满足方程2 *(arr [i]和arr [j])+(arr [i] ^ arr [j ])=K。

例子:

天真的方法:最简单的方法是从数组中生成所有可能的对,并针对每个对检查该对是否满足给定的方程式。
时间复杂度: O(N 2 )
辅助空间: O(1)

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

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

  • 现在,该问题简化为“两次和”问题,并且任务减少为对总和等于K的对进行计数
  • 初始化一个无序映射(例如mp )和一个变量(例如cnt) ,以计算满足给定条件的对的数量。
  • 遍历数组以及每个元素:
    • 如果mp [K – arr [i]]不为零,则将其值添加到cnt
    • 更新Maparr [i]的频率。
  • 打印cnt作为答案。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count number of pairs
// satisfying the given conditions
void countPairs(int arr[], int N, int K)
{
    // Stores the frequency of array elements
    unordered_map mp;
 
    // Stores the total number of pairs
    int cnt = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Add it to cnt
        cnt += mp[K - arr[i]];
 
        // Update frequency of
        // current array element
        mp[arr[i]]++;
    }
 
    // Print the count
    cout << cnt;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 5, 4, 8, 7 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given value of K
    int K = 9;
 
    countPairs(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG
{
 
    // Function to count number of pairs
    // satisfying the given conditions
    static void countPairs(int arr[], int N, int K)
    {
       
        // Stores the frequency of array elements
        Map mp = new HashMap<>();
 
        // Stores the total number of pairs
        int cnt = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++)
        {
 
            // Add it to cnt
            if (mp.get(K - arr[i]) != null)
                cnt += mp.get(K - arr[i]);
 
            // Update frequency of
            // current array element
            mp.put(arr[i], mp.get(arr[i]) == null
                               ? 1
                               : mp.get(arr[i]) + 1);
        }
 
        // Print the count
        System.out.println(cnt);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array
        int arr[] = { 1, 5, 4, 8, 7 };
 
        // Size of the array
        int N = arr.length;
 
        // Given value of K
        int K = 9;
 
        countPairs(arr, N, K);
    }
}
 
// This code is contributed by Dharanendra L V


Python3
# Python3 program for the above approach
from collections import defaultdict
 
# Function to count number of pairs
# satisfying the given conditions
def countPairs(arr, N, K) :
     
    # Stores the frequency of array elements
    mp = defaultdict(int)
 
    # Stores the total number of pairs
    cnt = 0
 
    # Traverse the array
    for i in range(N):
 
        # Add it to cnt
        cnt += mp[K - arr[i]]
 
        # Update frequency of
        # current array element
        mp[arr[i]] += 1
     
    # Prthe count
    print(cnt)
 
# Driver Code
# Given array
arr = [ 1, 5, 4, 8, 7 ]
 
# Size of the array
N = len(arr)
 
# Given value of K
K = 9
countPairs(arr, N, K)
 
# This code is contributed by sanjoy_62.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
    // Function to count number of pairs
    // satisfying the given conditions
    static void countPairs(int[] arr, int N, int K)
    {
       
        // Stores the frequency of array elements
        Dictionary mp
            = new Dictionary();
 
        // Stores the total number of pairs
        int cnt = 0;
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Add it to cnt
            if (mp.ContainsKey(K - arr[i]))
                cnt += mp[K - arr[i]];
 
            // Update frequency of
            // current array element
            if (mp.ContainsKey(arr[i])) {
               
                var val = mp[arr[i]];
                mp.Remove(arr[i]);
                mp.Add(arr[i], val + 1);
            }
            else {
               
                mp.Add(arr[i], 1);
            }
        }
 
        // Print the count
        Console.WriteLine(cnt);
    }
 
    // Driver Code
    static public void Main()
    {
 
        // Given array
        int[] arr = { 1, 5, 4, 8, 7 };
 
        // Size of the array
        int N = arr.Length;
 
        // Given value of K
        int K = 9;
        countPairs(arr, N, K);
    }
}
 
// This code is contributed by Dharanendra L V


输出:
2

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