📜  总和为 2 的幂的对数 | 2套

📅  最后修改于: 2021-10-27 08:24:28             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是计算对(arr[i], arr[j])的最大数量,使得arr[i] + arr[j]是 2 的幂。

例子:

朴素的方法:解决问题的最简单的方法是从给定的数组中生成所有可能的对,对于每一对,检查对的和是否是 2 的幂。
时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:上述方法可以使用HashMap进行优化。请按照以下步骤解决问题:

  • 创建一个Map来存储数组arr[]的每个元素的频率。
  • 初始化变量ans以存储总和等于2 的任意幂的对的计数。
  • 遍历范围[0, 31]并生成 2 的所有幂,即2 02 31
  • 为生成的每个 2 的幂遍历给定数组并检查map[key – arr[j]] 是否存在,其中key等于2 i
  • 如果发现为真,则通过map[key – arr[j]]增加count ,因为对 (s) (arr[j], key – arr[j])存在且总和等于2
  • 最后,打印count / 2作为必需的答案。

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
 
#include 
using namespace std;
 
// Function to count all pairs
// whose sum is a power of two
int countPair(int arr[], int n)
{
    // Stores the frequency of
    // each element of the array
    map m;
 
    // Update frequency of
    // array elements
    for (int i = 0; i < n; i++)
        m[arr[i]]++;
 
    // Stores count of
    // required pairs
    int ans = 0;
 
    for (int i = 0; i < 31; i++) {
 
        // Current power of 2
        int key = pow(2, i);
 
        // Traverse the array
        for (int j = 0; j < n; j++) {
 
            int k = key - arr[j];
 
            // If pair does not exist
            if (m.find(k) == m.end())
                continue;
 
            // Increment count of pairs
            else
                ans += m[k];
 
            if (k == arr[j])
                ans++;
        }
    }
 
    // Return the count of pairs
    return ans / 2;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 8, 2, 10, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPair(arr, n) << endl;
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
 
class GFG {
    // Function to count all pairs
    // whose sum is power of two
    static int countPair(int[] arr, int n)
    {
        // Stores the frequency of
        // each element of the array
        Map m
            = new HashMap<>();
 
        // Update the frequency of
        // array elements
        for (int i = 0; i < n; i++)
            m.put(arr[i], m.getOrDefault(
                            arr[i], 0)
                            + 1);
 
        // Stores the count of pairs
        int ans = 0;
 
        // Generate powers of 2
        for (int i = 0; i < 31; i++) {
 
            // Generate current power of 2
            int key = (int)Math.pow(2, i);
 
            // Traverse the array
            for (int j = 0; j < arr.length;
                j++) {
 
                int k = key - arr[j];
 
                // Increase ans by m[k], if
                // pairs with sum 2^i exists
                ans += m.getOrDefault(k, 0);
 
                // Increase ans again if k = arr[j]
                if (k == arr[j])
                    ans++;
            }
        }
 
        // Return count of pairs
        return ans / 2;
    }
 
    // Driver function
    public static void main(String[] args)
    {
        int[] arr = { 1, -1, 2, 3 };
        int n = arr.length;
        System.out.println(countPair(arr, n));
    }
}


Python3
# Python3 program to implement
# the above approach
from math import pow
 
# Function to count all pairs
# whose sum is a power of two
def countPair(arr, n):
     
    # Stores the frequency of
    # each element of the array
    m = {}
 
    # Update frequency of
    # array elements
    for i in range(n):
        m[arr[i]] = m.get(arr[i], 0) + 1
 
    # Stores count of
    # required pairs
    ans = 0
 
    for i in range(31):
         
        # Current power of 2
        key = int(pow(2, i))
 
        # Traverse the array
        for j in range(n):
            k = key - arr[j]
 
            # If pair does not exist
            if k not in m:
                continue
 
            # Increment count of pairs
            else:
                ans += m.get(k, 0)
 
            if (k == arr[j]):
                ans += 1
 
    # Return the count of pairs
    return ans // 2
 
# Driver Code
if __name__ == '__main__':
     
    arr =  [ 1, 8, 2, 10, 6 ]
    n = len(arr)
     
    print(countPair(arr, n))
 
# This code is contributed by SURENDRA_GANGWAR


Javascript


输出:

5

时间复杂度: O(NlogN)

辅助空间: O(1)

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