Eliminar elementos que aparecen estrictamente menos de k veces

Dada una array de enteros, elimine todos los elementos que aparecen estrictamente menos de k veces.
Ejemplos: 

Input : arr[] = {1, 2, 2, 3, 2, 3, 4}
        k = 2
Output : 2 2 3 2 3
Explanation : {1, 4} appears less than 2 times.

Acercarse :  

  • Tome un mapa hash, que almacenará la frecuencia de todos los elementos en la array.
  • Ahora, atraviesa una vez más.
  • Eliminar los elementos que aparecen estrictamente menos de k veces.
  • De lo contrario, imprímelo.

C++

// C++ program to remove the elements which
// appear strictly less than k times from the array.
#include "iostream"
#include "unordered_map"
using namespace std;
 
void removeElements(int arr[], int n, int k)
{
    // Hash map which will store the
    // frequency of the elements of the array.
    unordered_map<int, int> mp;
 
    for (int i = 0; i < n; ++i) {
        // Incrementing the frequency
        // of the element by 1.
        mp[arr[i]]++;
    }
 
    for (int i = 0; i < n; ++i) {
 
        // Print the element which appear
        // more than or equal to k times.
        if (mp[arr[i]] >= k) {
            cout << arr[i] << " ";
        }
    }
}
 
int main()
{
    int arr[] = { 1, 2, 2, 3, 2, 3, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    removeElements(arr, n, k);
    return 0;
}

Java

// Java program to remove the elements which
// appear strictly less than k times from the array.
import java.util.HashMap;
 
class geeks
{
 
    public static void removeElements(int[] arr,
                                        int n, int k)
    {
         
        // Hash map which will store the
        // frequency of the elements of the array.
        HashMap<Integer, Integer> mp = new HashMap<>();
 
        for (int i = 0; i < n; ++i)
        {
 
            // Incrementing the frequency
            // of the element by 1.
            if (!mp.containsKey(arr[i]))
                mp.put(arr[i], 1);
            else
            {
                int x = mp.get(arr[i]);
                mp.put(arr[i], ++x);
            }
        }
 
        for (int i = 0; i < n; ++i)
        {
             
            // Print the element which appear
            // more than or equal to k times.
            if (mp.get(arr[i]) >= k)
                System.out.print(arr[i] + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 2, 3, 2, 3, 4 };
        int n = arr.length;
        int k = 2;
        removeElements(arr, n, k);
    }
}
 
// This code is contributed by
// sanjeev2552

Python3

# Python3 program to remove the elements which
# appear strictly less than k times from the array.
def removeElements(arr, n, k):
     
    # Hash map which will store the
    # frequency of the elements of the array.
    mp = dict()
 
    for i in range(n):
         
        # Incrementing the frequency
        # of the element by 1.
        mp[arr[i]] = mp.get(arr[i], 0) + 1
 
    for i in range(n):
 
        # Print the element which appear
        # more than or equal to k times.
        if (arr[i] in mp and mp[arr[i]] >= k):
            print(arr[i], end = " ")
 
# Driver Code
arr = [1, 2, 2, 3, 2, 3, 4]
n = len(arr)
k = 2
removeElements(arr, n, k)
 
# This code is contributed by Mohit Kumar

C#

// C# program to remove the elements which
// appear strictly less than k times from the array.
using System;
using System.Collections.Generic;
  
class geeks
{
  
    public static void removeElements(int[] arr,
                                        int n, int k)
    {
          
        // Hash map which will store the
        // frequency of the elements of the array.
        Dictionary<int, int> mp = new Dictionary<int, int>();
  
        for (int i = 0; i < n; ++i)
        {
  
            // Incrementing the frequency
            // of the element by 1.
            if (!mp.ContainsKey(arr[i]))
                mp.Add(arr[i], 1);
            else
            {
                int x = mp[arr[i]];
                mp[arr[i]] = mp[arr[i]] + ++x;
            }
        }
  
        for (int i = 0; i < n; ++i)
        {
              
            // Print the element which appear
            // more than or equal to k times.
            if (mp[arr[i]] >= k)
                Console.Write(arr[i] + " ");
        }
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = { 1, 2, 2, 3, 2, 3, 4 };
        int n = arr.Length;
        int k = 2;
        removeElements(arr, n, k);
    }
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
 
// JavaScript program to remove the elements which
// appear strictly less than k times from the array.
 
function removeElements(arr,n,k)
{
    // Hash map which will store the
        // frequency of the elements of the array.
        let mp = new Map();
  
        for (let i = 0; i < n; ++i)
        {
  
            // Incrementing the frequency
            // of the element by 1.
            if (!mp.has(arr[i]))
                mp.set(arr[i], 1);
            else
            {
                let x = mp.get(arr[i]);
                mp.set(arr[i], ++x);
            }
        }
  
        for (let i = 0; i < n; ++i)
        {
              
            // Print the element which appear
            // more than or equal to k times.
            if (mp.get(arr[i]) >= k)
                document.write(arr[i] + " ");
        }
}
 
// Driver code
 
let arr=[ 1, 2, 2, 3, 2, 3, 4 ];
let n = arr.length;
let k = 2;
removeElements(arr, n, k);
 
 
// This code is contributed by unknown2108
 
</script>
Producción: 

2 2 3 2 3

 

Complejidad de tiempo: O(N)

Método n.º 2: uso de las funciones integradas de Python:

  • Cuente las frecuencias de cada elemento usando la función Counter()
  • Atraviesa la array.
  • Eliminar los elementos que aparecen estrictamente menos de k veces.
  • De lo contrario, imprímelo.

A continuación se muestra la implementación del enfoque anterior:

Python3

# Python3 program to remove the elements which
# appear strictly less than k times from the array.
from collections import Counter
 
def removeElements(arr, n, k):
 
    # Calculating frequencies using
    # Counter function
    freq = Counter(arr)
    for i in range(n):
 
        # Print the element which appear
        # more than or equal to k times.
        if (freq[arr[i]] >= k):
            print(arr[i], end=" ")
 
 
# Driver Code
arr = [1, 2, 2, 3, 2, 3, 4]
n = len(arr)
k = 2
removeElements(arr, n, k)
 
# This code is contributed by vikkycirus

Producción:

2 2 3 2 3 

Publicación traducida automáticamente

Artículo escrito por imdhruvgupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *