📜  未排序数组中每个元素计数的累积频率

📅  最后修改于: 2021-10-27 07:33:19             🧑  作者: Mango

给定一个未排序的数组。任务是使用计数数组计算数组每个元素的累积频率

例子:

Input : arr[] = [1, 2, 2, 1, 3, 4]
Output :1->2
        2->4
        3->5
        4->6

Input : arr[] = [1, 1, 1, 2, 2, 2]
Output :1->3
        2->6 

一个简单的解决方案是使用两个嵌套循环。外循环从左到右选取一个未被访问的元素。内部循环计算其出现次数并将出现次数标记为已访问。该解决方案的时间复杂度为 O(n*n),所需的辅助空间为 O(n)。

更好的解决方案是使用排序。我们对数组进行排序,以便相同的元素聚集在一起。排序后,我们线性遍历元素并计算它们的频率。

一个有效的解决方案是使用散列。在一组对中插入元素及其频率。由于集合以排序顺序存储唯一值,因此它将以排序顺序存储所有元素及其频率。在集合中迭代并通过在每一步添加之前的频率来打印频率。
下面是上述方法的实现:

C++
#include 
using namespace std;
 
// Function to print the cumulative frequency according to
// the order given
void countFreq(int a[], int n)
{
   
    // Declaring a map so values get inserted in a sorted
    // manner
    map m;
   
    // Inserting values into the map
    for (int i = 0; i < n; i++) {
        m[a[i]]++;
    }
   
    // Variable to store the count of previous number
    // cumulative frequency
    int cumul = 0;
    for (auto v : m) {
        cout << v.first << " " << v.second + cumul
             << endl;
        cumul += v.second;
    }
}
 
int main()
{
    int arr[] = { 1, 3, 2, 4, 2, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}
 
// This code is contributed by Vinayak Pareek (Kargil)


Java
// Java program to count cumlative
// frequencies of elements in an unsorted array.
import java.util.*;
 
class GFG
{
    static void countFreq(int[] a, int n)
    {
 
        // Insert elements and their
        // frequencies in hash map.
        HashMap hm = new HashMap<>();
        for (int i = 0; i < n; i++)
            hm.put(a[i], hm.get(a[i]) == null ?
                     1 : hm.get(a[i]) + 1);
 
        // Declare a Map
        SortedMap st = new TreeMap<>();
 
        // insert the element and
        // and insert its frequency in a set
        for (HashMap.Entry x : hm.entrySet())
        {
            st.put(x.getKey(), x.getValue());
        }
 
        int cumul = 0;
 
        // iterate the set and print the
        // cumulative frequency
        for (SortedMap.Entry x : st.entrySet())
        {
            cumul += x.getValue();
            System.out.println(x.getKey() + " " + cumul);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] a = { 1, 3, 2, 4, 2, 1 };
        int n = a.length;
        countFreq(a, n);
    }
}
 
// This code is contributed by
// sanjeev2552


Python3
# Python3 program to count cumlative
# frequencies of elements in an unsorted array.
def countFreq(a, n):
 
    # Insert elements and their
    # frequencies in hash map.
    hm = {}
    for i in range(0, n):
        hm[a[i]] = hm.get(a[i], 0) + 1
 
    # Declare a set
    st = set()
 
    # Insert the element and
    # its frequency in a set
    for x in hm:
        st.add((x, hm[x]))
 
    cumul = 0
 
    # Iterate the set and print
    # the cumulative frequency
    for x in sorted(st):
        cumul += x[1]
        print(x[0], cumul)
 
# Driver Code
if __name__ == "__main__":
 
    a = [1, 3, 2, 4, 2, 1]
    n = len(a)
    countFreq(a, n)
     
# This code is contributed by Rituraj Jain


C#
// C# program to count cumlative
// frequencies of elements in an
// unsorted array.
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG{
     
static void countFreq(int[] a, int n)
{
     
    // Insert elements and their
    // frequencies in hash map.
    Dictionary hm = new Dictionary();
    for(int i = 0; i < n; i++)
    {
        if (hm.ContainsKey(a[i]))
        {
            hm[a[i]]++;
        }
        else
        {
            hm[a[i]] = 1;
        }
    }
 
    int cumul = 0;
 
    // Iterate the set and print the
    // cumulative frequency
    foreach(KeyValuePair x in hm.OrderBy(key => key.Key))
    {
        cumul += x.Value;
        Console.Write(x.Key + " " + cumul + "\n");
    }
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] a = { 1, 3, 2, 4, 2, 1 };
    int n = a.Length;
     
    countFreq(a, n);
}
}
 
// This code is contributed by rutvik_56


Javascript


C++
// C++ program to print the cumulative frequency
// according to the order given
#include 
using namespace std;
 
// Function to print the cumulative frequency
// according to the order given
void countFreq(int a[], int n)
{
    // Insert elements and their
    // frequencies in hash map.
    unordered_map hm;
    for (int i=0; i" << cumul << endl;
       }
       // mark the hash 0
       // as the element's cumulative frequency
       // has been printed
       hm[a[i]]=0;
   }
}
 
// Driver Code
int main()
{
    int a[] = {1, 3, 2, 4, 2, 1};
    int n = sizeof(a)/sizeof(a[0]);
    countFreq(a, n);
    return 0;
}


Java
// Java program to print the cumulative frequency
// according to the order given
class GFG
{
 
// Function to print the cumulative frequency
// according to the order given
static void countFreq(int a[], int n)
{
    // Insert elements and their
    // frequencies in hash map.
    int hm[] = new int[n];
    for (int i = 0; i < n; i++)
        hm[a[i]]++;
    int cumul = 0;
     
// traverse in the array
for(int i = 0; i < n; i++)
{
    // add the frequencies
    cumul += hm[a[i]];
         
    // if the element has not been
    // visited previously
    if(hm[a[i]] != 0)
    {
        System.out.println(a[i] + "->" + cumul);
    }
    // mark the hash 0
    // as the element's cumulative frequency
    // has been printed
    hm[a[i]] = 0;
}
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = {1, 3, 2, 4, 2, 1};
    int n = a.length;
    countFreq(a, n);
}
}
 
// This code has been contributed by 29AjayKumar


Python3
# Python3 program to print the cumulative
# frequency according to the order given
 
# Function to print the cumulative frequency
# according to the order given
def countFreq(a, n):
 
    # Insert elements and their
    # frequencies in hash map.
    hm = dict()
    for i in range(n):
        hm[a[i]] = hm.get(a[i], 0) + 1
 
    cumul = 0
 
    # traverse in the array
    for i in range(n):
 
    # add the frequencies
        cumul += hm[a[i]]
 
    # if the element has not been
    # visited previously
        if(hm[a[i]] > 0):
            print(a[i], "->", cumul)
             
    # mark the hash 0
    # as the element's cumulative
    # frequency has been printed
        hm[a[i]] = 0
 
# Driver Code
a = [1, 3, 2, 4, 2, 1]
n = len(a)
countFreq(a, n)
 
# This code is contributed by mohit kumar


C#
// C# program to print the cumulative frequency
// according to the order given
using System;
 
class GFG
{
 
// Function to print the cumulative frequency
// according to the order given
static void countFreq(int []a, int n)
{
    // Insert elements and their
    // frequencies in hash map.
    int []hm = new int[n];
    for (int i = 0; i < n; i++)
        hm[a[i]]++;
    int cumul = 0;
     
// traverse in the array
for(int i = 0; i < n; i++)
{
    // add the frequencies
    cumul += hm[a[i]];
         
    // if the element has not been
    // visited previously
    if(hm[a[i]] != 0)
    {
        Console.WriteLine(a[i] + "->" + cumul);
    }
     
    // mark the hash 0
    // as the element's cumulative frequency
    // has been printed
    hm[a[i]] = 0;
}
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = {1, 3, 2, 4, 2, 1};
    int n = a.Length;
    countFreq(a, n);
}
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


输出:
1 2
2 4
3 5
4 6

解决方案的时间复杂度为O(n log n)

如果我们需要根据第一次出现的顺序出现元素的频率怎么办?
例如,一个数组[2, 4, 1, 2, 1, 3, 4],应该先打印2的频率,然后是4,然后是1,最后是3。
方法:散列元素出现的次数。遍历数组并打印累积频率。打印元素及其累积频率后,将该元素的出现散列为 0,这样如果它在遍历时出现在数组的后半部分,则不会再次打印。
下面是上述方法的实现:

C++

// C++ program to print the cumulative frequency
// according to the order given
#include 
using namespace std;
 
// Function to print the cumulative frequency
// according to the order given
void countFreq(int a[], int n)
{
    // Insert elements and their
    // frequencies in hash map.
    unordered_map hm;
    for (int i=0; i" << cumul << endl;
       }
       // mark the hash 0
       // as the element's cumulative frequency
       // has been printed
       hm[a[i]]=0;
   }
}
 
// Driver Code
int main()
{
    int a[] = {1, 3, 2, 4, 2, 1};
    int n = sizeof(a)/sizeof(a[0]);
    countFreq(a, n);
    return 0;
}

Java

// Java program to print the cumulative frequency
// according to the order given
class GFG
{
 
// Function to print the cumulative frequency
// according to the order given
static void countFreq(int a[], int n)
{
    // Insert elements and their
    // frequencies in hash map.
    int hm[] = new int[n];
    for (int i = 0; i < n; i++)
        hm[a[i]]++;
    int cumul = 0;
     
// traverse in the array
for(int i = 0; i < n; i++)
{
    // add the frequencies
    cumul += hm[a[i]];
         
    // if the element has not been
    // visited previously
    if(hm[a[i]] != 0)
    {
        System.out.println(a[i] + "->" + cumul);
    }
    // mark the hash 0
    // as the element's cumulative frequency
    // has been printed
    hm[a[i]] = 0;
}
}
 
// Driver Code
public static void main(String[] args)
{
    int a[] = {1, 3, 2, 4, 2, 1};
    int n = a.length;
    countFreq(a, n);
}
}
 
// This code has been contributed by 29AjayKumar

蟒蛇3

# Python3 program to print the cumulative
# frequency according to the order given
 
# Function to print the cumulative frequency
# according to the order given
def countFreq(a, n):
 
    # Insert elements and their
    # frequencies in hash map.
    hm = dict()
    for i in range(n):
        hm[a[i]] = hm.get(a[i], 0) + 1
 
    cumul = 0
 
    # traverse in the array
    for i in range(n):
 
    # add the frequencies
        cumul += hm[a[i]]
 
    # if the element has not been
    # visited previously
        if(hm[a[i]] > 0):
            print(a[i], "->", cumul)
             
    # mark the hash 0
    # as the element's cumulative
    # frequency has been printed
        hm[a[i]] = 0
 
# Driver Code
a = [1, 3, 2, 4, 2, 1]
n = len(a)
countFreq(a, n)
 
# This code is contributed by mohit kumar

C#

// C# program to print the cumulative frequency
// according to the order given
using System;
 
class GFG
{
 
// Function to print the cumulative frequency
// according to the order given
static void countFreq(int []a, int n)
{
    // Insert elements and their
    // frequencies in hash map.
    int []hm = new int[n];
    for (int i = 0; i < n; i++)
        hm[a[i]]++;
    int cumul = 0;
     
// traverse in the array
for(int i = 0; i < n; i++)
{
    // add the frequencies
    cumul += hm[a[i]];
         
    // if the element has not been
    // visited previously
    if(hm[a[i]] != 0)
    {
        Console.WriteLine(a[i] + "->" + cumul);
    }
     
    // mark the hash 0
    // as the element's cumulative frequency
    // has been printed
    hm[a[i]] = 0;
}
}
 
// Driver Code
public static void Main(String[] args)
{
    int []a = {1, 3, 2, 4, 2, 1};
    int n = a.Length;
    countFreq(a, n);
}
}
 
/* This code contributed by PrinciRaj1992 */

Javascript


输出:
1->2
3->3
2->5
4->6

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