Encuentre la frecuencia de cada elemento en una array de rango limitado en menos de O (n) tiempo

Dada una array ordenada arr[] de enteros positivos, la tarea es encontrar la frecuencia de cada elemento de la array. Suponga que todos los elementos de la array son menores que alguna constante M.
Nota: haga esto sin atravesar la array completa. es decir, la complejidad temporal esperada es menor que O(n). 

Ejemplos: 

Entrada: arr[] = [1, 1, 1, 2, 3, 3, 5,
               5, 8, 8, 8, 9, 9, 10] 
Salida: El elemento 1 ocurre 3 veces El
elemento 2 ocurre 1 vez El
elemento 3 ocurre 2 veces
El elemento 5 ocurre 2 veces
El elemento 8 ocurre 3 veces
El elemento 9 ocurre 2 veces
El elemento 10 ocurre 1 vez
 

Entrada: arr[] = [2, 2, 6, 6, 7, 7, 7, 11] 
Salida: El elemento 2 ocurre 2 veces El
elemento 6 ocurre 2 veces El
elemento 7 ocurre 3 veces El
elemento 11 ocurre 1 vez

Método 1: Este método utiliza la técnica de Búsqueda Lineal sin utilizar espacio auxiliar.

  • Enfoque:   la idea es atravesar la array de entrada e incrementar la frecuencia del elemento si el elemento actual y el elemento anterior son iguales; de lo contrario, restablecer la frecuencia e imprimir el elemento y su frecuencia.
  • Algoritmo: 
    • Inicialice la frecuencia a 1 y el índice a 1.
    • Recorra la array desde la posición de índice y verifique si el elemento actual es igual al elemento anterior.
    • En caso afirmativo, incremente la frecuencia y el índice y repita el paso 2. De lo contrario, imprima el elemento y su frecuencia y repita el paso 2.
    • Por último (caso de la esquina), imprima el último elemento y su frecuencia.

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

C++

// C++ program to count number of occurrences of
// each element in the array in O(n) time and O(1) space
 
#include <iostream>
using namespace std;
void findFrequencies(int ele[], int n)
{
    int freq = 1;
    int idx = 1;
    int element = ele[0];
    while (idx < n) {
        // check if the current element is equal to
        // previous element.
        if (ele[idx - 1] == ele[idx]) {
            freq++;
            idx++;
        }
        else {
            cout << element << " " << freq << endl;
            element = ele[idx];
            idx++;
           
            // reset the frequency
            freq = 1;
        }
    }
   
    // print the last element and its frequency
    cout << element << " " << freq;
}
 
int main()
{
    cout << "---frequencies in a sorted array----" << endl;
    int arr[]
        = { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 };
    int n = sizeof(arr) / sizeof(arr[0]);
    findFrequencies(arr, n);
}
 
// This code is contributed by anushkaseehh

Java

// Java program to count number of occurrences of
// each element in the array in O(n) time and O(1) space
 
import java.io.*;
import java.util.*;
class GFG
{
public static void findFrequencies(int[] ele, int n)
{
    int freq = 1;
    int idx = 1;
    int element = ele[0];
    while (idx < n) {
        // check if the current element is equal to
        // previous element.
        if (ele[idx - 1] == ele[idx]) {
            freq++;
            idx++;
        }
        else {
            System.out.println(element+" "+freq);
            element = ele[idx];
            idx++;
            
            // reset the frequency
            freq = 1;
        }
    }
    
    // print the last element and its frequency
    System.out.println(element+" "+freq);
}
  
 
// Driver function
public static void main (String[] args) {
 
    System.out.println("---frequencies in a sorted array----");
    int[] arr
        = { 10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 };
    int n = arr.length;
    findFrequencies(arr, n);
}
}
 
// This code is contributed by Pushpesh raj.

Python3

# python program to count number of occurrences of
# each element in the array in O(n) time and O(1) space
def findFrequencies(ele, n):
 
    freq = 1
    idx = 1
    element = ele[0]
    while (idx < n):
       
        # check if the current element is equal to
        # previous element.
        if (ele[idx - 1] == ele[idx]):
            freq += 1
            idx += 1
         
        else:
            print(element , " " ,freq);
            element = ele[idx]
            idx += 1
           
            # reset the frequency
            freq = 1
         
    # print the last element and its frequency
    print(element , " " , freq);
 
print( "---frequencies in a sorted array----" );
arr = [10, 20, 30, 30, 30, 40, 50, 50, 50, 50, 70 ];
n = len(arr)
findFrequencies(arr, n)
 
# This code is contributed by shivanisinghss2110

C#

// C# program to count number of occurrences of
// each element in the array in O(n) time and O(1) space
using System;
class GFG {
 
    public static void findFrequencies(int[] ele)
    {
        int freq = 1;
        int idx = 1;
        int element = ele[0];
        while (idx < ele.Length)
        {
           
            // check if the current element is equal to
            // previous element.
            if (ele[idx - 1] == ele[idx]) {
                freq++;
                idx++;
            }
            else {
                Console.WriteLine(element + " " + freq);
                element = ele[idx];
                idx++;
               
                // reset the frequency
                freq = 1;
            }
        }
       
        // print the last element and its frequency
        Console.WriteLine(element + " " + freq);
    }
   
    // Driver code
    public static void Main(String[] args)
    {
        Console.WriteLine(
            "---frequencies in a sorted array----");
        findFrequencies(new int[] { 10, 20, 30, 30, 30, 40,
                                    50, 50, 50, 50, 70 });
    }
}

Javascript

<script>
// JavaScript program to count number of occurrences of
// each element in the array in O(n) time and O(1) space
    function void findFrequencies(ele)
    {
        var freq = 1;
        var idx = 1;
        var element = ele[0];
        while (idx < ele.length)
        {
         
            // check if the current element is equal to
            // previous element.
            if (ele[idx - 1] == ele[idx]) {
                freq++;
                idx++;
            }
            else
            {
                document.write(element + " " + freq);
                element = ele[idx];
                idx++;
                 
                // reset the frequency
                freq = 1;
            }
        }
         
        // print the last element and its frequency
        document.write(element + " " + freq);
    }
     
    // Driver code
        document.write(
            "---frequencies in a sorted array----");
        findFrequencies(new var[] { 10, 20, 30, 30, 30, 40,
                                    50, 50, 50, 50, 70 });
     
// This code is contributed by shivanisinghss2110
</script>
Producción

---frequencies in a sorted array----
10 1
20 1
30 3
40 1
50 4
70 1

  

Método 2 : Este método utiliza la técnica de Búsqueda Lineal para resolver lo siguiente. 

  • Enfoque: la idea es atravesar la array de entrada y, para cada elemento distinto de la array, almacenar su frecuencia en un HashMap y, finalmente, imprimir el HashMap.
  • Algoritmo: 
    1. Cree un HashMap para asignar la frecuencia al elemento, es decir, para almacenar el par elemento-frecuencia.
    2. Atraviesa la array de principio a fin.
    3. Para cada elemento de la array, actualice la frecuencia, es decir, hm[array[i]]++
    4. Atraviese el HashMap e imprima el par de frecuencias del elemento.

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

C++

// C++ program to count number of occurrences of
// each element in the array #include <iostream>
#include <bits/stdc++.h>
using namespace std;
 
// It prints number of
// occurrences of each element in the array.
void findFrequency(int arr[], int n)
{
    // HashMap to store frequencies
    unordered_map<int, int> mp;
 
    // traverse the array
    for (int i = 0; i < n; i++) {
        // update the frequency
        mp[arr[i]]++;
    }
 
    // traverse the hashmap
    for (auto i : mp) {
        cout << "Element " << i.first << " occurs "
             << i.second << " times" << endl;
    }
}
 
// Driver function
int main()
{
    int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5,
                  8, 8, 8, 9, 9, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findFrequency(arr, n);
 
    return 0;
}

Java

// Java program to count number
// of occurrences of each
// element in the array
import java.io.*;
import java.util.*;
class GFG
{
 
  // It prints number of
  // occurrences of each
  // element in the array.
  static void findFrequency(int [] arr,
                            int n)
  {
    Map<Integer, Integer> mp
      = new HashMap<Integer, Integer>();
 
    // traverse the array
    for (int i = 0; i < n; i++)
    {
 
      // update the frequency
      if (!mp.containsKey(arr[i]))
        mp.put(arr[i],0);
 
      mp.put(arr[i],mp.get(arr[i])+1);
    }
 
    // traverse the hashmap
    for (Map.Entry<Integer, Integer> kvp : mp.entrySet())
    {
      System.out.println("Element " + kvp.getKey() +
                         " occurs " + kvp.getValue() +
                         " times");
    }
  }
 
  // Driver function
  public static void main (String[] args) {
 
 
    int [] arr = {1, 1, 1, 2,
                  3, 3, 5, 5,
                  8, 8, 8, 9,
                  9, 10};
    int n = arr.length;
    findFrequency(arr, n);
  }
}
 
// This code is contributed by avanitrachhadiya2155

Python3

# Python program to count number of occurrences of
# each element in the array #include <iostream>
 
# It prints number of
# occurrences of each element in the array.
def findFrequency(arr, n):
     
    # HashMap to store frequencies
    mp = {}
 
    # traverse the array
    for i in range(n):
 
        # update the frequency
        if arr[i] not in mp:
            mp[arr[i]] = 0
        mp[arr[i]] += 1
         
    # traverse the hashmap
    for i in mp:
        print("Element", i, "occurs", mp[i], "times")
     
# Driver function
arr = [1, 1, 1, 2, 3, 3, 5, 5,8, 8, 8, 9, 9, 10]
n = len(arr)
 
findFrequency(arr, n)
     
# This code is contributed by shubhamsingh10

C#

// C# program to count number
// of occurrences of each
// element in the array
using System;
using System.Collections.Generic;
class GFG{
 
// It prints number of
// occurrences of each
// element in the array.
static void findFrequency(int [] arr,
                          int n)
{
  // HashMap to store frequencies
  Dictionary <int,
              int > mp =
              new Dictionary<int,
                             int>();
 
  // traverse the array
  for (int i = 0; i < n; i++)
  {
    // update the frequency
    if (!mp.ContainsKey(arr[i]))
      mp[arr[i]] = 0;
 
    mp[arr[i]]++;
  }
 
  // traverse the hashmap
  foreach(KeyValuePair<int,
                       int> kvp in mp)
    Console.WriteLine("Element " + kvp.Key +
                      " occurs " + kvp.Value +
                      " times");
}
 
// Driver function
public static void Main()
{
  int [] arr = {1, 1, 1, 2,
                3, 3, 5, 5,
                8, 8, 8, 9,
                9, 10};
  int n = arr.Length;
  findFrequency(arr, n);
}
}
 
// This code is contributed by Chitranayal

Javascript

<script>
 
// Javascript program to count number
// of occurrences of each
// element in the array
 
// It prints number of
// occurrences of each
// element in the array.
function findFrequency(arr, n)
{
    let mp = new Map();
  
    // Traverse the array
    for(let i = 0; i < n; i++)
    {
  
        // Update the frequency
        if (!mp.has(arr[i]))
            mp.set(arr[i],0);
         
        mp.set(arr[i], mp.get(arr[i]) + 1);
    }
  
    // Traverse the hashmap
    for(let [key, value] of mp.entries())
    {
        document.write("Element " + key +
                       " occurs " + value +
                       " times<br>");
    }
}
 
// Driver code
let arr = [ 1, 1, 1, 2, 3, 3, 5,
            5, 8, 8, 8, 9, 9, 10 ];
let n = arr.length;
 
findFrequency(arr, n);
 
// This code is contributed by patel2127
 
</script>
Producción

Element 10 occurs 1 times
Element 2 occurs 1 times
Element 9 occurs 2 times
Element 1 occurs 3 times
Element 8 occurs 3 times
Element 3 occurs 2 times
Element 5 occurs 2 times

Análisis de Complejidad: 

  • Complejidad de tiempo: O (n), solo se necesita un recorrido de la array.
  • Complejidad espacial: O(n), para almacenar los elementos en el HashMap O(n) se necesita espacio extra.

Método 3 : este método utiliza la técnica de búsqueda binaria para llegar a la solución.  

  • Enfoque: El problema se puede resolver en menos de O(n) tiempo si todos sus elementos están ordenados, es decir, si existen elementos similares en el arreglo, entonces los elementos están en un subarreglo contiguo o se puede decir que si los extremos de un subarreglo están mismo entonces todos los elementos dentro del subarreglo son iguales. Entonces, el recuento de ese elemento es el tamaño del subarreglo y no es necesario contar todos los elementos de ese subarreglo. 
     
  • Algoritmo: 
    1. Cree un HashMap ( hm ) para almacenar la frecuencia de los elementos.
    2. Cree una función recursiva que acepte una array y un tamaño.
    3. Compruebe si el primer elemento de la array es igual al último elemento. Si es igual, todos los elementos son iguales y actualizan la frecuencia por hm[array[0]+=size
    4. De lo contrario, divida la array en dos mitades iguales y llame a la función recursivamente para ambas mitades.
    5. Recorra el hashmap e imprima el par de frecuencias del elemento.

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

C++

// C++ program to count number of occurrences of
// each element in the array in less than O(n) time
#include <iostream>
#include <vector>
using namespace std;
 
// A recursive function to count number of occurrences
// for each element in the array without traversing
// the whole array
void findFrequencyUtil(int arr[], int low, int high,
                       vector<int>& freq)
{
    // If element at index low is equal to element
    // at index high in the array
    if (arr[low] == arr[high]) {
        // increment the frequency of the element
        // by count of elements between high and low
        freq[arr[low]] += high - low + 1;
    }
    else {
        // Find mid and recurse for left and right
        // subarray
        int mid = (low + high) / 2;
        findFrequencyUtil(arr, low, mid, freq);
        findFrequencyUtil(arr, mid + 1, high, freq);
    }
}
 
// A wrapper over recursive function
// findFrequencyUtil(). It print number of
// occurrences of each element in the array.
void findFrequency(int arr[], int n)
{
    // create a empty vector to store frequencies
    // and initialize it by 0. Size of vector is
    // maximum value (which is last value in sorted
    // array) plus 1.
    vector<int> freq(arr[n - 1] + 1, 0);
 
    // Fill the vector with frequency
    findFrequencyUtil(arr, 0, n - 1, freq);
 
    // Print the frequencies
    for (int i = 0; i <= arr[n - 1]; i++)
        if (freq[i] != 0)
            cout << "Element " << i << " occurs "
                 << freq[i] << " times" << endl;
}
 
// Driver function
int main()
{
    int arr[] = { 1, 1, 1, 2, 3, 3, 5, 5,
                  8, 8, 8, 9, 9, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findFrequency(arr, n);
 
    return 0;
}

Java

// Java program to count number of occurrences of
// each element in the array in less than O(n) time
import java.util.*;
 
class GFG {
 
    // A recursive function to count number of occurrences
    // for each element in the array without traversing
    // the whole array
    static void findFrequencyUtil(int arr[], int low,
                                  int high, int[] freq)
    {
        // If element at index low is equal to element
        // at index high in the array
        if (arr[low] == arr[high]) {
            // increment the frequency of the element
            // by count of elements between high and low
            freq[arr[low]] += high - low + 1;
        }
        else {
            // Find mid and recurse for left and right
            // subarray
            int mid = (low + high) / 2;
            findFrequencyUtil(arr, low, mid, freq);
            findFrequencyUtil(arr, mid + 1, high, freq);
        }
    }
 
    // A wrapper over recursive function
    // findFrequencyUtil(). It print number of
    // occurrences of each element in the array.
    static void findFrequency(int arr[], int n)
    {
        // create a empty vector to store frequencies
        // and initialize it by 0. Size of vector is
        // maximum value (which is last value in sorted
        // array) plus 1.
        int[] freq = new int[arr[n - 1] + 1];
 
        // Fill the vector with frequency
        findFrequencyUtil(arr, 0, n - 1, freq);
 
        // Print the frequencies
        for (int i = 0; i <= arr[n - 1]; i++)
            if (freq[i] != 0)
                System.out.println("Element " + i + " occurs " + freq[i] + " times");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 1, 1, 2, 3, 3, 5,
                      5, 8, 8, 8, 9, 9, 10 };
        int n = arr.length;
 
        findFrequency(arr, n);
    }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python 3 program to count number of occurrences of
# each element in the array in less than O(n) time
 
# A recursive function to count number of occurrences
# for each element in the array without traversing
# the whole array
def findFrequencyUtil(arr, low, high, freq):
     
    # If element at index low is equal to element
    # at index high in the array
    if (arr[low] == arr[high]):
         
        # increment the frequency of the element
        # by count of elements between high and low
        freq[arr[low]] += high - low + 1
     
    else:
         
        # Find mid and recurse for left 
        # and right subarray
        mid = int((low + high) / 2)
        findFrequencyUtil(arr, low, mid, freq)
        findFrequencyUtil(arr, mid + 1, high, freq)
     
# A wrapper over recursive function
# findFrequencyUtil(). It print number of
# occurrences of each element in the array.
def findFrequency(arr, n):
     
    # create a empty vector to store frequencies
    # and initialize it by 0. Size of vector is
    # maximum value (which is last value in sorted
    # array) plus 1.
    freq = [0 for i in range(n - 1 + 1)]
     
    # Fill the vector with frequency
    findFrequencyUtil(arr, 0, n - 1, freq)
 
    # Print the frequencies
    for i in range(0, arr[n - 1] + 1, 1):
        if (freq[i] != 0):
            print("Element", i, "occurs",
                        freq[i], "times")
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 1, 1, 2, 3, 3, 5,
           5, 8, 8, 8, 9, 9, 10]
    n = len(arr)
    findFrequency(arr, n)
     
# This code is contributed by
# Surendra_Gangwar

C#

// C# program to count number of occurrences of
// each element in the array in less than O(n) time
using System;
 
class GFG {
 
    // A recursive function to count number of occurrences
    // for each element in the array without traversing
    // the whole array
    static void findFrequencyUtil(int[] arr, int low,
                                  int high, int[] freq)
    {
        // If element at index low is equal to element
        // at index high in the array
        if (arr[low] == arr[high]) {
            // increment the frequency of the element
            // by count of elements between high and low
            freq[arr[low]] += high - low + 1;
        }
        else {
            // Find mid and recurse for left and right
            // subarray
            int mid = (low + high) / 2;
            findFrequencyUtil(arr, low, mid, freq);
            findFrequencyUtil(arr, mid + 1, high, freq);
        }
    }
 
    // A wrapper over recursive function
    // findFrequencyUtil(). It print number of
    // occurrences of each element in the array.
    static void findFrequency(int[] arr, int n)
    {
        // create a empty vector to store frequencies
        // and initialize it by 0. Size of vector is
        // maximum value (which is last value in sorted
        // array) plus 1.
        int[] freq = new int[arr[n - 1] + 1];
 
        // Fill the vector with frequency
        findFrequencyUtil(arr, 0, n - 1, freq);
 
        // Print the frequencies
        for (int i = 0; i <= arr[n - 1]; i++)
            if (freq[i] != 0)
                Console.WriteLine("Element " + i + " occurs " + freq[i] + " times");
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 1, 1, 1, 2, 3, 3, 5,
                      5, 8, 8, 8, 9, 9, 10 };
        int n = arr.Length;
 
        findFrequency(arr, n);
    }
}
 
// This code is contributed by Princi Singh

Javascript

<script>
// Javascript program to count number of occurrences of
// each element in the array in less than O(n) time
     
    // A recursive function to count number of occurrences
    // for each element in the array without traversing
    // the whole array
    function findFrequencyUtil(arr, low, high, freq)
    {
     
        // If element at index low is equal to element
        // at index high in the array
        if (arr[low] == arr[high])
        {
         
            // increment the frequency of the element
            // by count of elements between high and low
            freq[arr[low]] += high - low + 1;
        }
        else
        {
         
            // Find mid and recurse for left and right
            // subarray
            let mid = Math.floor((low + high) / 2);
            findFrequencyUtil(arr, low, mid, freq);
            findFrequencyUtil(arr, mid + 1, high, freq);
        }
    }
     
    // A wrapper over recursive function
    // findFrequencyUtil(). It print number of
    // occurrences of each element in the array.
    function findFrequency(arr, n)
    {
     
        // create a empty vector to store frequencies
        // and initialize it by 0. Size of vector is
        // maximum value (which is last value in sorted
        // array) plus 1.
        let freq = new Array(arr[n - 1] + 1);
         
        for(let i = 0; i < arr[n - 1] + 1; i++)
        {
            freq[i] = 0;
        }
         
        // Fill the vector with frequency
        findFrequencyUtil(arr, 0, n - 1, freq);
  
        // Print the frequencies
        for (let i = 0; i <= arr[n - 1]; i++)
            if (freq[i] != 0)
                document.write("Element " + i + " occurs " + freq[i] + " times<br>");
    }
     
    // Driver Code
    let arr = [1, 1, 1, 2, 3, 3, 5,
                      5, 8, 8, 8, 9, 9, 10 ];
    let n = arr.length;
    findFrequency(arr, n);
     
    // This code is contributed by rag2127.
</script>
Producción

Element 1 occurs 3 times
Element 2 occurs 1 times
Element 3 occurs 2 times
Element 5 occurs 2 times
Element 8 occurs 3 times
Element 9 occurs 2 times
Element 10 occurs 1 times

Análisis de Complejidad: 

  • Complejidad temporal: O(m log n). 
    Donde m es el número de elementos distintos en la array de tamaño n. Dado que m <= M (una constante) (los elementos están en un rango limitado), la complejidad temporal de esta solución es O (log n).
  • Complejidad espacial: O(n). 
    Para almacenar los elementos en el HashMap O(n) se necesita espacio extra.

Método 4 

En este método, usamos la misma array que el mapa hash modificando su contenido.

Hagamos un ensayo en seco con un ejemplo. 

arr = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };

Paso 1: – Resta 1 de cada elemento de la array

array = {0 ,0 ,0 ,1 ,2 ,2 ,4 ,4 ,7 ,7 ,7 ,8 ,8 ,9 }

Paso 2: – Agregue n al índice al que apunta el elemento de array actual.

por ejemplo :- 

cuando i=0, arr[arr[0]%n] = 0 sumando n a arr[0], arr[0] = 14;

cuando i=1, arr[arr[1]%n] = 14 sumando n a arr[0] ,arr[0] = 28;

De manera similar, al encontrar la array modificada de la misma manera, obtendremos la array como  

arr = {42, 14, 28, 1, 30, 2, 4, 46, 35, 21, 7, 8, 8, 9}

Paso 3: – Ahora, en el paso 2, si ha notado que agregamos el valor n al índice al que apunta un elemento en particular. Entonces, si tenemos más de una vez un elemento que apunta al mismo índice, en ese caso, la división del número modificado con la n nos da la frecuencia del número. 

por ejemplo 

en i=0; array[0] =42; arr[0] / n = 3 significa que 0 apareció tres veces en el arreglo modificado como se puede ver en el arr del paso 1.

en i=1; array[1] =14; arr[1]/14 = 1 significa que 1 apareció una vez en la array modificada como puede ver en el arr del paso 1.

y de manera similar para otros valores que podamos calcular.

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

C++

// C++ program to count number of occurrences of
// each element in the array #include <iostream>
#include <bits/stdc++.h>
using namespace std;
 
// It prints number of occurrences of each element in the
// array.
void findFrequency(int input[], int n)
{
    for (int i = 0; i < n; i++)
        input[i]--;
 
    for (int i = 0; i < n; i++)
        input[input[i] % n] += n;
 
    for (int i = 0; i < n; i++) {
        if (input[i] / n)
            cout << "Element " << (i + 1) << " occurs "
                 << input[i] / n << " times" << endl;
        // Change the element back to original value
        input[i] = input[i] % n + 1;
    }
}
 
// Driver function
int main()
{
    int arr[]
        = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findFrequency(arr, n);
 
    return 0;
}
 
// This code is contributed by aditya kumar(adiyakumar129)

Java

// Java program to count number of occurrences of each
// element in the array
import java.io.*;
import java.util.*;
class GFG {
 
    // It prints number of occurrences of each element in
    // the array.
    static void findFrequency(int[] input, int n)
    {
        for (int i = 0; i < n; i++)
            input[i]--;
 
        for (int i = 0; i < n; i++)
            input[input[i] % n] += n;
 
        for (int i = 0; i < n; i++) {
            if ((input[i] / n) != 0)
                System.out.println(
                    "Element " + (i + 1) + " occurs "
                    + input[i] / n + " times");
            // Change the element back to original value
            input[i] = input[i] % n + 1;
        }
    }
 
    // Driver function
    public static void main(String[] args)
    {
        int[] arr
            = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };
        int n = arr.length;
        findFrequency(arr, n);
    }
}
 
// This code is contributed by aditya kumar(adiyakumar129)

Python3

# Javascript program to count number of occurrences of
# each element in the array
 
# It prints number of
# occurrences of each element in the array.
def findFrequency(input, n):
    for i in range(n):
        input[i] -= 1
 
    for i in range(n):
        input[input[i] % n] += n
 
    for i in range(n):
        if input[i] // n:
            print("Element", i + 1, "occurs", input[i] // n, "times")
 
        # change element back to original value
        input[i] = input[i] % n + 1
 
# Driver function
arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10]
n = len(arr)
 
findFrequency(arr, n)
 
# This code is contributed by phasing17

C#

// C# program to count number of occurrences of each element
// in the array
using System;
 
public class GFG {
 
    // It prints number of occurrences of each element in
    // the array.
    static void findFrequency(int[] input, int n)
    {
        for (int i = 0; i < n; i++)
            input[i]--;
 
        for (int i = 0; i < n; i++)
            input[input[i] % n] += n;
 
        for (int i = 0; i < n; i++) {
            if ((input[i] / n) != 0)
                Console.WriteLine(
                    "Element " + (i + 1) + " occurs "
                    + input[i] / n + " times");
            // Change the element back to original value
            input[i] = input[i] % n + 1;
        }
    }
 
    // Driver function
    public static void Main(String[] args)
    {
        int[] arr
            = { 1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10 };
        int n = arr.Length;
        findFrequency(arr, n);
    }
}
 
// This code is contributed by shikhasingrajput

Javascript

<script>
// Javascript program to count number of occurrences of
// each element in the array
 
// It prints number of
// occurrences of each element in the array.
function findFrequency(input, n)
{
    for (let i = 0; i < n; i++)
        input[i]--;
 
    for (let i = 0; i < n; i++)
        input[input[i] % n] += n;
 
    console.log(input)
    for (let i = 0; i < n; i++) {
        if (Math.floor(input[i] / n))
            document.write("Element " + (i + 1) +
            " occurs " + Math.floor(input[i] / n) + " times <br>");
             
        // Change the element back to original value
        input[i] = input[i] % n + 1;
    }
}
 
// Driver function
let arr = [1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10];
let n = arr.length;
 
findFrequency(arr, n);
 
// This code is contributed by Saurabh Jaiswal
</script>
Producción

Element 1 occurs 3 times
Element 2 occurs 1 times
Element 3 occurs 2 times
Element 5 occurs 2 times
Element 8 occurs 3 times
Element 9 occurs 2 times
Element 10 occurs 1 times

https://youtu.be/B2hI-QPoisk 
Este artículo es una contribución de Aditya Goel . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 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 *