📌  相关文章
📜  找出线性时间内出现频率最高的 k

📅  最后修改于: 2021-09-07 02:54:36             🧑  作者: Mango

给定一个整数数组,我们需要打印 k 个最频繁的元素。如果有平局,我们需要优先选择第一个出现的元素。
例子:

我们在下面的帖子中讨论了两种方法
查找给定数组中出现次数最多的 k 个数字
让我们先谈谈一个简单的解决方案,它可以在平局的情况下以任何顺序打印。然后我们将讨论采用顺序的解决方案。

这个想法是使用带有频率索引的哈希。我们首先将计数存储在哈希中。然后我们遍历哈希并使用频率作为索引来存储具有给定频率的元素。这里的重要因素是,最大频率可以是 n。所以大小为 n+1 的数组会很好。

C++
// C++ implementation to find k numbers with most
// occurrences in the given array
#include 
using namespace std;
 
// funnction to print the k numbers with most occurrences
void print_N_mostFrequentNumber(int arr[], int n, int k)
{
    // unordered_map 'um' implemented as frequency
    // hash table
    unordered_map um;
    for (int i = 0; i < n; i++)
        um[arr[i]]++;
 
    // Use frequencies as indexes and put
    // elements with given frequency in a
    // vector (related to a frequency)
    vector freq[n + 1];
    for (auto x : um)
        freq[x.second].push_back(x.first);
 
    // Initialize count of items printed
    int count = 0;
 
    // Traverse the frequency array from
    // right side as we need the most
    // frequent items.
    for (int i = n; i >= 0; i--) {
 
        // Print items of current frequency
        for (int x : freq[i]) {
            cout << x << " ";
            count++;
            if (count == k)
                return;
        }
    }
}
 
// Driver program to test above
int main()
{
    int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    print_N_mostFrequentNumber(arr, n, k);
    return 0;
}


Java
// Java implementation to find k elements with max occurence.
import java.util.*;
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int n, int k)
    {
        Map mp = new HashMap();
 
        // Put count of all the distinct elements in Map
        // with element as the key & count as the value.
        for (int i = 0; i < n; i++) {
 
            // Get the count for the element if already
            // present in the Map or get the default value
            // which is 0.
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Initialize an array list of array lists
        List > freq = new ArrayList >();
        for (int i = 0; i <= n; i++)
            freq.add(new ArrayList());
 
        // Use frequencies as indexes and add corresponding
        // values to the list
        for (Map.Entry x : mp.entrySet())
            freq.get(x.getValue()).add(x.getKey());
 
        // Traverse freq[] from right side.
        int count = 0;
        for (int i = n; i >= 0; i--) {
            for (int x : freq.get(i)) {
                System.out.println(x);
                count++;
                if (count == k)
                    return;
            }
        }
    }
 
    // Driver Code to test the code.
    public static void main(String[] args)
    {
        int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int n = arr.length;
        int k = 2;
        print_N_mostFrequentNumber(arr, n, k);
    }
}


Python3
# Python3 implementation to find k numbers
# with most occurrences in the given array
 
# Function to prthe k numbers with most occurrences
def print_N_mostFrequentNumber(arr, n, k):
     
    # unordered_map 'um' implemented as
    # frequency hash table
    um = {}
    for i in range(n):
        um[arr[i]] =  um.get(arr[i], 0) + 1
 
    # Use frequencies as indexes and put
    # elements with given frequency in a
    # vector (related to a frequency)
    freq = [[] for i in range(n + 1)]
    for x in um:
        freq[um[x]].append(x)
 
    # Initialize count of items printed
    count = 0
 
    # Traverse the frequency array from
    # right side as we need the most
    # frequent items.
    for i in range(n, -1, -1):
         
        # Print items of current frequency
        for x in sorted(freq[i])[::-1]:
            print(x, end = " ")
            count += 1
             
            if (count == k):
                return
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 3, 1, 4, 4, 5, 2, 6, 1 ]
    n = len(arr)
    k = 2
     
    print_N_mostFrequentNumber(arr, n, k)
 
# This code is contributed by mohit kumar 29


C#
// C# implementation to find
// k elements with max occurence.
using System;
using System.Collections.Generic;
class KFrequentNumbers{
 
static void print_N_mostFrequentNumber(int[] arr,
                                       int n, int k)
{
  Dictionary mp = new Dictionary();
 
  // Put count of all the
  // distinct elements in Map
  // with element as the key
  // & count as the value.
  for (int i = 0; i < n; i++)
  {
    // Get the count for the
    // element if already
    // present in the Map
    // or get the default value
    // which is 0.
    if(mp.ContainsKey(arr[i]))
    {
      mp[arr[i]] = mp[arr[i]] + 1;
    }
    else
    {
      mp.Add(arr[i], 1);
    }
  }
 
  // Initialize an array
  // list of array lists
  List > freq =
            new List >();
   
  for (int i = 0; i <= n; i++)
    freq.Add(new List());
 
  // Use frequencies as indexes
  // and add corresponding
  // values to the list
  foreach (KeyValuePair x in mp)
    freq[x.Value].Add(x.Key);
 
  // Traverse []freq from
  // right side.
  int count = 0;
  for (int i = n; i >= 0; i--)
  {
    foreach (int x in freq[i])
    {
      Console.WriteLine(x);
      count++;
      if (count == k)
        return;
    }
  }
}
 
// Driver Code to test the code.
public static void Main(String[] args)
{
  int []arr = {3, 1, 4, 4,
               5, 2, 6, 1};
  int n = arr.Length;
  int k = 2;
  print_N_mostFrequentNumber(arr, n, k);
}
}
 
// This code is contributed by Princi Singh


C++
// C++ implementation to find k numbers with most
// occurrences in the given array
#include 
using namespace std;
 
// function to print the k numbers with most occurrences
void print_N_mostFrequentNumber(int arr[], int n, int k)
{
    // unordered_map 'um' implemented as frequency
    // hash table
    unordered_map um;
    for (int i = 0; i < n; i++)
        um[arr[i]]++;
 
    // Use frequencies as indexes and put
    // elements with given frequency in a
    // vector (related to a frequency)
    vector freq[n + 1];
    for (int i = 0; i < n; i++) {
        int f = um[arr[i]];
        if (f != -1) {
            freq[f].push_back(arr[i]);
            um[arr[i]] = -1;
        }
    }
 
    // Initialize count of items printed
    int count = 0;
 
    // Traverse the frequency array from
    // right side as we need the most
    // frequent items.
    for (int i = n; i >= 0; i--) {
 
        // Print items of current frequency
        for (int x : freq[i]) {
            cout << x << " ";
            count++;
            if (count == k)
                return;
        }
    }
}
 
// Driver program to test above
int main()
{
    int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    print_N_mostFrequentNumber(arr, n, k);
    return 0;
}


Java
// Java implementation to find k elements with max occurence.
import java.util.*;
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int n, int k)
    {
        Map mp = new HashMap();
 
        // Put count of all the distinct elements in Map
        // with element as the key & count as the value.
        for (int i = 0; i < n; i++) {
 
            // Get the count for the element if already
            // present in the Map or get the default value
            // which is 0.
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Initialize an array list of array lists
        List > freq = new ArrayList >();
        for (int i = 0; i <= n; i++)
            freq.add(new ArrayList());
 
        // Use frequencies as indexes and add corresponding
        // values to the list
        for (int i = 0; i < n; i++) {
            int f = mp.get(arr[i]);
            if (f != -1) {
                freq.get(f).add(arr[i]);
                mp.put(arr[i], -1);
            }
        }
 
        // Traverse freq[] from right side.
        int count = 0;
        for (int i = n; i >= 0; i--) {
            for (int x : freq.get(i)) {
                System.out.println(x);
                count++;
                if (count == k)
                    return;
            }
        }
    }
 
    // Driver Code to test the code.
    public static void main(String[] args)
    {
        int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int n = arr.length;
        int k = 3;
        print_N_mostFrequentNumber(arr, n, k);
    }
}


C#
// C# implementation to find k elements
// with max occurence.
using System;
using System.Collections.Generic;
 
class GFG{
     
static void print_N_mostFrequentNumber(int[] arr,
                                       int n, int k)
{
    Dictionary mp = new Dictionary();
 
    // Put count of all the distinct
    // elements in Map with element
    // as the key & count as the value.
    for(int i = 0; i < n; i++)
    {
         
        // Get the count for the element
        // if already present in the Map
        // or get the default value which is 0.
        if (mp.ContainsKey(arr[i]))
            mp[arr[i]]++;
        else
            mp.Add(arr[i], 0);
    }
 
    // Initialize an array list of array lists
    List> freq = new List>();
    for(int i = 0; i <= n; i++)
        freq.Add(new List());
 
    // Use frequencies as indexes and
    // add corresponding values to
    // the list
    for(int i = 0; i < n; i++)
    {
        int f = mp[arr[i]];
        if (f != -1)
        {
            freq[f].Add(arr[i]);
 
            if (mp.ContainsKey(arr[i]))
                mp[arr[i]] = -1;
            else
                mp.Add(arr[i], 0);
        }
    }
 
    // Traverse []freq from right side.
    int count = 0;
    for(int i = n; i >= 0; i--)
    {
        foreach(int x in freq[i])
        {
            Console.Write(x);
            Console.Write(" ");
            count++;
             
            if (count == k)
                return;
        }
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int n = arr.Length;
    int k = 3;
     
    print_N_mostFrequentNumber(arr, n, k);
}
}
 
// This code is contributed by Amit Katiyar


输出:
4 1

时间复杂度: O(n)
辅助空间: O(n)按第一次出现打印。为了保持所需的顺序,我们遍历原始数组而不是映射。为了避免重复,我们需要在映射中将处理过的条目标记为 -1。

C++

// C++ implementation to find k numbers with most
// occurrences in the given array
#include 
using namespace std;
 
// function to print the k numbers with most occurrences
void print_N_mostFrequentNumber(int arr[], int n, int k)
{
    // unordered_map 'um' implemented as frequency
    // hash table
    unordered_map um;
    for (int i = 0; i < n; i++)
        um[arr[i]]++;
 
    // Use frequencies as indexes and put
    // elements with given frequency in a
    // vector (related to a frequency)
    vector freq[n + 1];
    for (int i = 0; i < n; i++) {
        int f = um[arr[i]];
        if (f != -1) {
            freq[f].push_back(arr[i]);
            um[arr[i]] = -1;
        }
    }
 
    // Initialize count of items printed
    int count = 0;
 
    // Traverse the frequency array from
    // right side as we need the most
    // frequent items.
    for (int i = n; i >= 0; i--) {
 
        // Print items of current frequency
        for (int x : freq[i]) {
            cout << x << " ";
            count++;
            if (count == k)
                return;
        }
    }
}
 
// Driver program to test above
int main()
{
    int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    print_N_mostFrequentNumber(arr, n, k);
    return 0;
}

Java

// Java implementation to find k elements with max occurence.
import java.util.*;
public class KFrequentNumbers {
    static void print_N_mostFrequentNumber(int[] arr, int n, int k)
    {
        Map mp = new HashMap();
 
        // Put count of all the distinct elements in Map
        // with element as the key & count as the value.
        for (int i = 0; i < n; i++) {
 
            // Get the count for the element if already
            // present in the Map or get the default value
            // which is 0.
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Initialize an array list of array lists
        List > freq = new ArrayList >();
        for (int i = 0; i <= n; i++)
            freq.add(new ArrayList());
 
        // Use frequencies as indexes and add corresponding
        // values to the list
        for (int i = 0; i < n; i++) {
            int f = mp.get(arr[i]);
            if (f != -1) {
                freq.get(f).add(arr[i]);
                mp.put(arr[i], -1);
            }
        }
 
        // Traverse freq[] from right side.
        int count = 0;
        for (int i = n; i >= 0; i--) {
            for (int x : freq.get(i)) {
                System.out.println(x);
                count++;
                if (count == k)
                    return;
            }
        }
    }
 
    // Driver Code to test the code.
    public static void main(String[] args)
    {
        int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 };
        int n = arr.length;
        int k = 3;
        print_N_mostFrequentNumber(arr, n, k);
    }
}

C#

// C# implementation to find k elements
// with max occurence.
using System;
using System.Collections.Generic;
 
class GFG{
     
static void print_N_mostFrequentNumber(int[] arr,
                                       int n, int k)
{
    Dictionary mp = new Dictionary();
 
    // Put count of all the distinct
    // elements in Map with element
    // as the key & count as the value.
    for(int i = 0; i < n; i++)
    {
         
        // Get the count for the element
        // if already present in the Map
        // or get the default value which is 0.
        if (mp.ContainsKey(arr[i]))
            mp[arr[i]]++;
        else
            mp.Add(arr[i], 0);
    }
 
    // Initialize an array list of array lists
    List> freq = new List>();
    for(int i = 0; i <= n; i++)
        freq.Add(new List());
 
    // Use frequencies as indexes and
    // add corresponding values to
    // the list
    for(int i = 0; i < n; i++)
    {
        int f = mp[arr[i]];
        if (f != -1)
        {
            freq[f].Add(arr[i]);
 
            if (mp.ContainsKey(arr[i]))
                mp[arr[i]] = -1;
            else
                mp.Add(arr[i], 0);
        }
    }
 
    // Traverse []freq from right side.
    int count = 0;
    for(int i = n; i >= 0; i--)
    {
        foreach(int x in freq[i])
        {
            Console.Write(x);
            Console.Write(" ");
            count++;
             
            if (count == k)
                return;
        }
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 3, 1, 4, 4, 5, 2, 6, 1 };
    int n = arr.Length;
    int k = 3;
     
    print_N_mostFrequentNumber(arr, n, k);
}
}
 
// This code is contributed by Amit Katiyar
输出:
1 4 3

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live