📌  相关文章
📜  删除最频繁出现的数组元素恰好 K 次

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

给定一个数组arr[] ,任务是删除最频繁出现的数组元素恰好K次。如果多个数组元素具有最大频率,则删除其中最小的。打印K 个删除的元素。

例子:

朴素的方法:最简单的方法是按升序对数组进行排序,并使用 Map 计算数组元素的频率。对于K 次操作,打印最频繁的元素并将其频率降低1

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to print the most frequent
// array element exactly K times
void maxFreqElements(int arr[],
                     int N, int K)
{
    // Stores frequency array element
    map mp;
 
    for (int i = 0; i < N; i++) {
 
        // Count frequency
        // of array element
        mp[arr[i]]++;
    }
 
    while (K > 0) {
 
        // Maximum array element
        int max = 0;
        int element;
 
        // Traverse the Map
        for (auto i : mp) {
 
            // Find the element with
            // maximum frequency
            if (i.second > max) {
                max = i.second;
 
                // If the frequency is maximum,
                // store that number in element
                element = i.first;
            }
        }
 
        // Print element as it contains the
        // element having highest frequency
        cout << element << " ";
 
        // Decrease the frequency
        // of the maximum array element
        mp[element]--;
 
        // Reduce the number of operations
        K--;
    }
}
 
// Driver Code
int main()
{
 
    // Given array
    int arr[] = { 1, 3, 2, 1, 4, 1 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given K
    int K = 2;
 
    maxFreqElements(arr, N, K);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
// Function to print the most frequent
// array element exactly K times
static void maxFreqElements(int arr[],
                     int N, int K)
{
   
    // Stores frequency array element
    HashMap mp = new HashMap();
  
    for (int i = 0; i < N; i++)
    {
  
        // Count frequency
        // of array element
        if(mp.containsKey(arr[i]))
            {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            }
            else
            {
                mp.put(arr[i], 1);
            }
    }
  
    while (K > 0)
    {
  
        // Maximum array element
        int max = 0;
        int element = 0;
  
        // Traverse the Map
        for (Map.Entry i : mp.entrySet())
        {
  
            // Find the element with
            // maximum frequency
            if (i.getValue() > max)
            {
                max = i.getValue();
  
                // If the frequency is maximum,
                // store that number in element
                element = i.getKey();
            }
        }
  
        // Print element as it contains the
        // element having highest frequency
        System.out.print(element + " ");
 
  
        // Decrease the frequency
        // of the maximum array element
        if(mp.containsKey(element))
            {
                mp.put(element, mp.get(element) + 1);
            }
            else
            {
                mp.put(element, 1);
            }
 
        // Reduce the number of operations
        K--;
    }
}
  
// Driver code
public static void main(String[] args)
{
    // Given array
    int[] arr = { 1, 3, 2, 1, 4, 1 };
      
    // Size of the array
    int N = arr.length;
      
    // Given K
    int K = 2;  
    maxFreqElements(arr, N, K);
}
}
 
// This code is contributed by susmitakundugoaldanga


Python3
# Python3 program for the above approach
 
# Function to print the most frequent
# array element exactly K times
def maxFreqElements(arr, N, K) :
 
    # Stores frequency array element
    mp = {}
 
    for i in range(N) :
 
        # Count frequency
        # of array element
        if arr[i] in mp :
            mp[arr[i]] += 1
        else :
            mp[arr[i]] = 1
 
    while (K > 0) :
 
        # Maximum array element
        Max = 0
 
        # Traverse the Map
        for i in mp :
 
            # Find the element with
            # maximum frequency
            if (mp[i] > Max) :
                Max = mp[i]
 
                # If the frequency is maximum,
                # store that number in element
                element = i
 
        # Print element as it contains the
        # element having highest frequency
        print(element, end = " ")
 
        # Decrease the frequency
        # of the maximum array element
        if element in mp :
            mp[element] -= 1
        else :
            mp[element] = -1
 
        # Reduce the number of operations
        K -= 1
 
# Given array
arr = [ 1, 3, 2, 1, 4, 1 ]
 
# Size of the array
N = len(arr) 
 
# Given K
K = 2
 
maxFreqElements(arr, N, K)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
using System.Collections.Generic; 
 
class GFG{
     
// Function to print the most frequent
// array element exactly K times
static void maxFreqElements(int[] arr,
                            int N, int K)
{
     
    // Stores frequency array element
    Dictionary mp = new Dictionary(); 
                                         
    for(int i = 0; i < N; i++)
    {
         
        // Count frequency
        // of array element
        if (mp.ContainsKey(arr[i]))
        {
            mp[arr[i]]++;
        }
        else
        {
            mp[arr[i]] = 1;
        }
    }
  
    while (K > 0)
    {
         
        // Maximum array element
        int max = 0;
        int element = 0;
  
        // Traverse the Map
        foreach(KeyValuePair i in mp)
        {
             
            // Find the element with
            // maximum frequency
            if (i.Value > max)
            {
                max = i.Value;
                 
                // If the frequency is maximum,
                // store that number in element
                element = i.Key;
            }
        }
  
        // Print element as it contains the
        // element having highest frequency
        Console.Write(element + " ");
  
        // Decrease the frequency
        // of the maximum array element
        if (mp.ContainsKey(element))
        {
            mp[element]--;
        }
        else
        {
            mp[element] = -1;
        }
  
        // Reduce the number of operations
        K--;
    }
}
 
// Driver Code
static void Main()
{
     
    // Given array
    int[] arr = { 1, 3, 2, 1, 4, 1 };
     
    // Size of the array
    int N = arr.Length;
     
    // Given K
    int K = 2;
     
    maxFreqElements(arr, N, K);
}
}
 
// This code is contributed by divyesh072019


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to sort the vector
// of vector of pair
bool cmp(pair p1, pair p2)
{
    // Check if frequency of p1 is
    // greater than frequency of p2
    if (p1.second > p2.second)
        return true;
 
    // If frequency of p1 and p2 is same
    else if (p1.second == p2.second) {
 
        // Check for the smallest element
        if (p1.first < p2.first)
            return true;
    }
    return false;
}
 
// Function to print the K most frequent
// elements after each removal
void maxFreqElements(int arr[], int N, int K)
{
    // Stores frequency of array elements
    map mp;
 
    // Pairs array element with frequency
    vector > v;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Count the frequencies
        mp[arr[i]]++;
 
        // Insert the element with its
        // current frequency into the vector
        v.push_back({ arr[i], mp[arr[i]] });
    }
 
    // Sort the vector according to
    // higher frequency and smaller
    // element if frequency is same
    sort(v.begin(), v.end(), cmp);
 
    // Print the first K elements
    // of the array
    for (int i = 0; i < K; i++)
        cout << v[i].first << " ";
}
 
// Driver Code
int main()
{
 
    // Given array
    int arr[] = { 1, 3, 2, 1, 4, 1 };
 
    // Given K
    int K = 2;
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    maxFreqElements(arr, N, K);
 
    return 0;
}


Java
// Java program for above approach
import java.util.*;
import java.lang.*;
 
class pair{
    int first,second;
     
    pair(int first, int second){
        this.first=first;
        this.second=second;
    }
}
class GFG{
  
// Function to print the K most frequent
// elements after each removal
static void maxFreqElements(int arr[], int N, int K)
{
    // Stores frequency of array elements
    Map mp=new HashMap<>();
  
    // Pairs array element with frequency
    ArrayList v=new ArrayList<>();
  
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
  
        // Count the frequencies
        mp.put(arr[i],mp.getOrDefault(arr[i],0)+1);
  
        // Insert the element with its
        // current frequency into the vector
        v.add(new pair( arr[i], mp.get(arr[i] )));
    }
  
    // Sort the vector according to
    // higher frequency and smaller
    // element if frequency is same
   Collections.sort(v,(a,b)->(a.second != b.second) ?
                    b.second-a.second:a.first-b.first);
  
    // Print the first K elements
    // of the array
    for (int i = 0; i < K; i++)
        System.out.print(v.get(i).first + " ");
}
   
   // Driver function
    public static void main (String[] args)
    {
      
    // Given array
    int arr[] = { 1, 3, 2, 1, 4, 1 };
  
    // Given K
    int K = 2;
  
    // Size of the array
    int N = arr.length;
  
    maxFreqElements(arr, N, K);
  
    }
}
 
// This code is contributed by offbeat


Python3
# Python 3 program for the above approach
 
# Function to sort the vector
# of vector of pair
 
# Function to print the K most frequent
# elements after each removal
def maxFreqElements(arr, N, K):
   
    # Stores frequency of array elements
    mp = {}
 
    # Pairs array element with frequency
    v = []
 
    # Traverse the array
    for i in range(N):
        # Count the frequencies
        mp[arr[i]] = mp.get(arr[i],0)+1
 
        # Insert the element with its
        # current frequency into the vector
        v.append([arr[i], mp.get(arr[i],0)])
 
    # Sort the vector according to
    # higher frequency and smaller
    c = [1, 1]
     
    # element if frequency is same
    v.sort(reverse = True)
 
    # Print the first K elements
    # of the array  
    for i in range(K):
        print(c[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [1, 3, 2, 1, 4, 1]
 
    # Given K
    K = 2
 
    # Size of the array
    N = len(arr)
 
    maxFreqElements(arr, N, K)
     
    # This code is contributed by SURANDRA_GANGWAR.


C#
// C# program for above approach
using System;
using System.Collections.Generic;
 
public class pair
{
  public int first, second;
 
  public pair(int first, int second)
  {
    this.first = first;
    this.second = second;
  }
}
 
public class GFG{
 
  static int Compare(KeyValuePair a, KeyValuePair b)
  {
    if(a.Value != b.Value)
    {
      return b.Value - a.Value;
    }
    else
    {
      return a.Key - b.Key;
    }
  }
 
  // Function to print the K most frequent
  // elements after each removal
  static void maxFreqElements(int[] arr, int N, int K)
  {
     
    // Stores frequency of array elements
    Dictionary mp = new Dictionary();
 
    // Pairs array element with frequency
    List> v = new List>();
     
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
 
      // Count the frequencies
      if(!mp.ContainsKey(arr[i]))
      {
        mp.Add(arr[i], 1);
      }
      else
      {
        mp[arr[i]]++;
      }
 
      // Insert the element with its
      // current frequency into the vector
      v.Add(new KeyValuePair( arr[i], mp[arr[i] ]));
    }
    v.Sort(Compare);
 
    // Print the first K elements
    // of the array
    for (int i = 0; i < K; i++)
    {
      Console.Write(v[i].Key + " ");
    }
  }
 
  // Driver function
  static public void Main ()
  {
 
    // Given array
    int[] arr = { 1, 3, 2, 1, 4, 1 };
 
    // Given K
    int K = 2;
 
    // Size of the array
    int N = arr.Length;
 
    maxFreqElements(arr, N, K);
  }
}
 
// This code is contributed by rag2127.


Javascript


输出:
1 1

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

有效的方法:这个想法是将元素数组与它们的计数一起存储在成对向量中,然后使用比较器按升序对成对向量进行排序。完成后,打印该对向量中的前K 个元素。

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

  • 初始化一个 Map 来存储数组元素的频率。初始化成对向量以存储{element, frequency}。
  • 按第二个值的降序对成对的向量进行排序。
  • 然后,打印前K对的数组元素作为答案。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to sort the vector
// of vector of pair
bool cmp(pair p1, pair p2)
{
    // Check if frequency of p1 is
    // greater than frequency of p2
    if (p1.second > p2.second)
        return true;
 
    // If frequency of p1 and p2 is same
    else if (p1.second == p2.second) {
 
        // Check for the smallest element
        if (p1.first < p2.first)
            return true;
    }
    return false;
}
 
// Function to print the K most frequent
// elements after each removal
void maxFreqElements(int arr[], int N, int K)
{
    // Stores frequency of array elements
    map mp;
 
    // Pairs array element with frequency
    vector > v;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Count the frequencies
        mp[arr[i]]++;
 
        // Insert the element with its
        // current frequency into the vector
        v.push_back({ arr[i], mp[arr[i]] });
    }
 
    // Sort the vector according to
    // higher frequency and smaller
    // element if frequency is same
    sort(v.begin(), v.end(), cmp);
 
    // Print the first K elements
    // of the array
    for (int i = 0; i < K; i++)
        cout << v[i].first << " ";
}
 
// Driver Code
int main()
{
 
    // Given array
    int arr[] = { 1, 3, 2, 1, 4, 1 };
 
    // Given K
    int K = 2;
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    maxFreqElements(arr, N, K);
 
    return 0;
}

Java

// Java program for above approach
import java.util.*;
import java.lang.*;
 
class pair{
    int first,second;
     
    pair(int first, int second){
        this.first=first;
        this.second=second;
    }
}
class GFG{
  
// Function to print the K most frequent
// elements after each removal
static void maxFreqElements(int arr[], int N, int K)
{
    // Stores frequency of array elements
    Map mp=new HashMap<>();
  
    // Pairs array element with frequency
    ArrayList v=new ArrayList<>();
  
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
  
        // Count the frequencies
        mp.put(arr[i],mp.getOrDefault(arr[i],0)+1);
  
        // Insert the element with its
        // current frequency into the vector
        v.add(new pair( arr[i], mp.get(arr[i] )));
    }
  
    // Sort the vector according to
    // higher frequency and smaller
    // element if frequency is same
   Collections.sort(v,(a,b)->(a.second != b.second) ?
                    b.second-a.second:a.first-b.first);
  
    // Print the first K elements
    // of the array
    for (int i = 0; i < K; i++)
        System.out.print(v.get(i).first + " ");
}
   
   // Driver function
    public static void main (String[] args)
    {
      
    // Given array
    int arr[] = { 1, 3, 2, 1, 4, 1 };
  
    // Given K
    int K = 2;
  
    // Size of the array
    int N = arr.length;
  
    maxFreqElements(arr, N, K);
  
    }
}
 
// This code is contributed by offbeat

蟒蛇3

# Python 3 program for the above approach
 
# Function to sort the vector
# of vector of pair
 
# Function to print the K most frequent
# elements after each removal
def maxFreqElements(arr, N, K):
   
    # Stores frequency of array elements
    mp = {}
 
    # Pairs array element with frequency
    v = []
 
    # Traverse the array
    for i in range(N):
        # Count the frequencies
        mp[arr[i]] = mp.get(arr[i],0)+1
 
        # Insert the element with its
        # current frequency into the vector
        v.append([arr[i], mp.get(arr[i],0)])
 
    # Sort the vector according to
    # higher frequency and smaller
    c = [1, 1]
     
    # element if frequency is same
    v.sort(reverse = True)
 
    # Print the first K elements
    # of the array  
    for i in range(K):
        print(c[i], end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array
    arr = [1, 3, 2, 1, 4, 1]
 
    # Given K
    K = 2
 
    # Size of the array
    N = len(arr)
 
    maxFreqElements(arr, N, K)
     
    # This code is contributed by SURANDRA_GANGWAR.

C#

// C# program for above approach
using System;
using System.Collections.Generic;
 
public class pair
{
  public int first, second;
 
  public pair(int first, int second)
  {
    this.first = first;
    this.second = second;
  }
}
 
public class GFG{
 
  static int Compare(KeyValuePair a, KeyValuePair b)
  {
    if(a.Value != b.Value)
    {
      return b.Value - a.Value;
    }
    else
    {
      return a.Key - b.Key;
    }
  }
 
  // Function to print the K most frequent
  // elements after each removal
  static void maxFreqElements(int[] arr, int N, int K)
  {
     
    // Stores frequency of array elements
    Dictionary mp = new Dictionary();
 
    // Pairs array element with frequency
    List> v = new List>();
     
    // Traverse the array
    for (int i = 0; i < N; i++)
    {
 
      // Count the frequencies
      if(!mp.ContainsKey(arr[i]))
      {
        mp.Add(arr[i], 1);
      }
      else
      {
        mp[arr[i]]++;
      }
 
      // Insert the element with its
      // current frequency into the vector
      v.Add(new KeyValuePair( arr[i], mp[arr[i] ]));
    }
    v.Sort(Compare);
 
    // Print the first K elements
    // of the array
    for (int i = 0; i < K; i++)
    {
      Console.Write(v[i].Key + " ");
    }
  }
 
  // Driver function
  static public void Main ()
  {
 
    // Given array
    int[] arr = { 1, 3, 2, 1, 4, 1 };
 
    // Given K
    int K = 2;
 
    // Size of the array
    int N = arr.Length;
 
    maxFreqElements(arr, N, K);
  }
}
 
// This code is contributed by rag2127.

Javascript


输出:
1 1

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

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