📌  相关文章
📜  按升序打印频率等于K的幂的所有数组元素

📅  最后修改于: 2021-05-17 19:02:30             🧑  作者: Mango

给定一个由N个整数和一个正整数K组成的数组arr [] ,任务是找到频率为K幂的数组元素,即K 1 ,K 2 ,K 3 ,依此类推

例子:

天真的方法:最简单的方法是计算每个数组元素的频率,如果任何元素的频率是K的完美幂,则打印该元素。否则,请检查下一个元素。

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

高效的方法:还可以通过使用哈希将HashMap中存储数组元素的频率存储在HashMap中,然后检查所需条件来优化上述方法。请按照以下步骤解决给定的问题:

  • 遍历给定的数组arr []并将每个数组元素的频率存储在Map中,例如M。
  • 现在,遍历地图并执行以下步骤:
    • 将映射中每个值的频率存储在变量中,例如F。
    • 如果(log F)/(log K)K (log F)/(log K)的值相同,则当前元素的频率为K的完美幂。因此,打印当前元素。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the array elements
// whose frequency is a power of K
void countFrequency(int arr[], int N,
                    int K)
{
    // Stores the frequency of each
    // array elements
    unordered_map freq;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Update frequency of
        // array elements
        freq[arr[i]]++;
    }
 
    // Traverse the map freq
    for (auto i : freq) {
 
        // Calculate the log value of the
        // current frequency with base K
        int lg = log(i.second) / log(K);
 
        // Find the power of K of log value
        int a = pow(K, lg);
 
        // If the values are equal
        if (a == i.second) {
 
            // Print the current element
            cout << i.first << " ";
        }
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 4, 4, 2,
                  1, 2, 3, 2, 2 };
    int K = 2;
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    countFrequency(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Function to find the array elements
    // whose frequency is a power of K
    static void countFrequency(int arr[], int N, int K)
    {
 
        // Stores the frequency of each
        // array elements
        HashMap freq = new HashMap<>();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Update frequency of
            // array elements
            freq.put(arr[i],
                     freq.getOrDefault(arr[i], 0) + 1);
        }
 
        // Traverse the map freq
        for (int key : freq.keySet()) {
 
            // Calculate the log value of the
            // current frequency with base K
            int lg = (int)(Math.log(freq.get(key))
                           / Math.log(K));
 
            // Find the power of K of log value
            int a = (int)(Math.pow(K, lg));
 
            // If the values are equal
            if (a == freq.get(key)) {
 
                // Print the current element
                System.out.print(key + " ");
            }
        }
    }
    // Driver Code
    public static void main(String[] args)
    {
 
        int arr[] = { 1, 4, 4, 2, 1, 2, 3, 2, 2 };
        int K = 2;
        int N = arr.length;
 
        // Function Call
        countFrequency(arr, N, K);
    }
}


Python3
# Python3 program for the above approach
 
# Function to find the array elements
from math import log
 
def countFrequency(arr, N, K):
   
    # Stores the frequency of each
    # array elements
    freq = {}
 
    # Traverse the array
    for i in range(N):
       
        # Update frequency of
        # array elements
        if (arr[i] in freq):
            freq[arr[i]] += 1
        else:
            freq[arr[i]] = 1
 
    # Traverse the map freq
    for key,value in freq.items():
       
        # Calculate the log value of the
        # current frequency with base K
        lg = log(value) // log(K)
 
        # Find the power of K of log value
        a = pow(K, lg)
 
        # If the values are equal
        if (a == value):
           
            # Print the current element
            print(key, end = " ")
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 4, 4, 2, 1, 2, 3, 2, 2]
    K = 2
    N = len(arr)
 
    # Function Call
    countFrequency(arr, N, K)
 
    # This code is contributed by bgangwar59.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
  
// Function to find the array elements
// whose frequency is a power of K
static void countFrequency(int []arr, int N,
                           int K)
{
     
    // Stores the frequency of each
    // array elements
    Dictionary freq = new Dictionary();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Update frequency of
        // array elements
        if (freq.ContainsKey(arr[i]))
            freq[arr[i]] += 1;
        else
            freq[arr[i]] = 1;
    }
 
    // Traverse the map freq
    foreach (KeyValuePair entry in freq)
    {
        int temp = entry.Key;
         
        // Calculate the log value of the
        // current frequency with base K
        int lg = (int)(Math.Log(entry.Value) /
                       Math.Log(K));
 
        // Find the power of K of log value
        int a = (int)Math.Pow(K, lg);
 
        // If the values are equal
        if (a == entry.Value)
        {
             
            // Print the current element
            Console.Write(entry.Key + " ");
        }
    }
}
 
// Driver Code
public static void Main()
{
    int []arr = { 1, 4, 4, 2,
                  1, 2, 3, 2, 2 };
    int K = 2;
    int N = arr.Length;
     
    // Function Call
    countFrequency(arr, N, K);
}
}
 
// This code is contributed by SURENDRA_GANGWAR


输出:
3 2 1 4

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