📌  相关文章
📜  计算数组元素的频率

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

给定一个可能包含重复项的数组,打印所有元素及其频率。

例子:

Input :  arr[] = {10, 20, 20, 10, 10, 20, 5, 20}
Output : 10 3
         20 4
         5  1

Input : arr[] = {10, 20, 20}
Output : 10 1
         20 2 

一个简单的解决方案是运行两个循环。对于每个项目计数次数,它都会发生。为避免重复打印,请跟踪处理的项目。

C++
// CPP program to count frequencies of array items
#include 
using namespace std;
 
void countFreq(int arr[], int n)
{
    // Mark all array elements as not visited
    vector visited(n, false);
 
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++) {
 
        // Skip this element if already processed
        if (visited[i] == true)
            continue;
 
        // Count frequency
        int count = 1;
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                visited[j] = true;
                count++;
            }
        }
        cout << arr[i] << " " << count << endl;
    }
}
 
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}


Java
// Java program to count frequencies of array items
import java.util.Arrays;
 
class GFG
{
public static void countFreq(int arr[], int n)
{
    boolean visited[] = new boolean[n];
     
    Arrays.fill(visited, false);
 
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++) {
 
        // Skip this element if already processed
        if (visited[i] == true)
            continue;
 
        // Count frequency
        int count = 1;
        for (int j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                visited[j] = true;
                count++;
            }
        }
        System.out.println(arr[i] + " " + count);
    }
}
 
// Driver code
public static void main(String []args)
{
    int arr[] = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = arr.length;
    countFreq(arr, n);
}
}
 
// This code contributed by Adarsh_Verma.


Python3
# Python 3 program to count frequencies
# of array items
def countFreq(arr, n):
     
    # Mark all array elements as not visited
    visited = [False for i in range(n)]
 
    # Traverse through array elements
    # and count frequencies
    for i in range(n):
         
        # Skip this element if already
        # processed
        if (visited[i] == True):
            continue
 
        # Count frequency
        count = 1
        for j in range(i + 1, n, 1):
            if (arr[i] == arr[j]):
                visited[j] = True
                count += 1
         
        print(arr[i], count)
 
# Driver Code
if __name__ == '__main__':
    arr = [10, 20, 20, 10, 10, 20, 5, 20]
    n = len(arr)
    countFreq(arr, n)
     
# This code is contributed by
# Shashank_Sharma


C#
// C# program to count frequencies of array items
using System;
 
class GFG
{
    public static void countFreq(int []arr, int n)
    {
        bool []visited = new bool[n];
     
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
     
            // Skip this element if already processed
            if (visited[i] == true)
                continue;
     
            // Count frequency
            int count = 1;
            for (int j = i + 1; j < n; j++)
            {
                if (arr[i] == arr[j])
                {
                    visited[j] = true;
                    count++;
                }
            }
            Console.WriteLine(arr[i] + " " + count);
        }
    }
     
    // Driver code
    public static void Main(String []args)
    {
        int []arr = new int[]{ 10, 20, 20, 10, 10, 20, 5, 20 };
        int n = arr.Length;
        countFreq(arr, n);
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript


C++
// CPP program to count frequencies of array items
#include 
using namespace std;
 
void countFreq(int arr[], int n)
{
    unordered_map mp;
 
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Traverse through map and print frequencies
    for (auto x : mp)
        cout << x.first << " " << x.second << endl;
}
 
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}


Java
// Java program to count frequencies of array items
import java.util.*;
 
class GFG
{
 
    static void countFreq(int arr[], int n)
    {
        Map mp = new HashMap<>();
 
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
            if (mp.containsKey(arr[i]))
            {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            }
            else
            {
                mp.put(arr[i], 1);
            }
        }
        // Traverse through map and print frequencies
        for (Map.Entry entry : mp.entrySet())
        {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.length;
        countFreq(arr, n);
    }
}
 
// This code contributed by Rajput-Ji


Python3
# Python3 program to count frequencies
# of array items
def countFreq(arr, n):
 
    mp = dict()
 
    # Traverse through array elements
    # and count frequencies
    for i in range(n):
        if arr[i] in mp.keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Traverse through map and print
    # frequencies
    for x in mp:
        print(x, " ", mp[x])
 
# Driver code
arr = [10, 20, 20, 10, 10, 20, 5, 20 ]
n = len(arr)
countFreq(arr, n)
 
# This code is contributed by
# Mohit kumar 29


C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    static void countFreq(int []arr, int n)
    {
        Dictionary mp = new Dictionary();
 
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
            if (mp.ContainsKey(arr[i]))
            {
                var val = mp[arr[i]];
                mp.Remove(arr[i]);
                mp.Add(arr[i], val + 1);
            }
            else
            {
                mp.Add(arr[i], 1);
            }
        }
         
        // Traverse through map and print frequencies
        foreach(KeyValuePair entry in mp)
        {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int []arr = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.Length;
        countFreq(arr, n);
    }
}
 
/* This code contributed by PrinciRaj1992 */


Javascript


C++
// CPP program to count frequencies of array items
#include 
using namespace std;
 
void countFreq(int arr[], int n)
{
    unordered_map mp;
 
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // To print elements according to first
    // occurrence, traverse array one more time
    // print frequencies of elements and mark
    // frequencies as -1 so that same element
    // is not printed multiple times.
    for (int i = 0; i < n; i++) {
      if (mp[arr[i]] != -1)
      {
          cout << arr[i] << " " << mp[arr[i]] << endl;
          mp[arr[i]] = -1;
      }
    }
}
 
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}


Java
// Java program to count frequencies of array items
import java.util.*;
 
class GFG
{
 
    static void countFreq(int arr[], int n)
    {
        Map mp = new HashMap<>();
 
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
            mp.put(arr[i], mp.get(arr[i]) == null ? 1 : mp.get(arr[i]) + 1);
        }
 
        // To print elements according to first
        // occurrence, traverse array one more time
        // print frequencies of elements and mark
        // frequencies as -1 so that same element
        // is not printed multiple times.
        for (int i = 0; i < n; i++)
        {
            if (mp.get(arr[i]) != -1)
            {
                System.out.println(arr[i] + " " + mp.get(arr[i]));
                mp.put(arr[i], -1);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.length;
        countFreq(arr, n);
    }
}
 
// This code contributed by Rajput-Ji


Python3
# Python3 program to count frequencies of array items
def countFreq(arr, n):
     
    mp = {}
     
    # Traverse through array elements and
    # count frequencies
    for i in range(n):
        if arr[i] not in mp:
            mp[arr[i]] = 0
        mp[arr[i]] += 1
         
    # To prelements according to first
    # occurrence, traverse array one more time
    # prfrequencies of elements and mark
    # frequencies as -1 so that same element
    # is not printed multiple times.
    for i in range(n):
        if (mp[arr[i]] != -1):
            print(arr[i],mp[arr[i]])
        mp[arr[i]] = -1
 
# Driver code
 
arr = [10, 20, 20, 10, 10, 20, 5, 20]
n = len(arr)
countFreq(arr, n)
 
# This code is contributed by shubhamsingh10


C#
// C# program to count frequencies of array items
using System;
using System.Collections.Generic;
 
class GFG
{
 
    static void countFreq(int []arr, int n)
    {
        Dictionary mp = new Dictionary();
 
        // Traverse through array elements and
        // count frequencies
         
        for (int i = 0 ; i < n; i++)
        {
            if(mp.ContainsKey(arr[i]))
            {
                var val = mp[arr[i]];
                mp.Remove(arr[i]);
                mp.Add(arr[i], val + 1);
            }
            else
            {
                mp.Add(arr[i], 1);
            }
        }
 
        // To print elements according to first
        // occurrence, traverse array one more time
        // print frequencies of elements and mark
        // frequencies as -1 so that same element
        // is not printed multiple times.
        for (int i = 0; i < n; i++)
        {
            if (mp.ContainsKey(arr[i]) && mp[arr[i]] != -1)
            {
                Console.WriteLine(arr[i] + " " + mp[arr[i]]);
                mp.Remove(arr[i]);
                mp.Add(arr[i], -1);
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.Length;
        countFreq(arr, n);
    }
}
 
// This code is contributed by Princi Singh


Javascript


Java
// Java program to count frequencies of
// integers in array using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfNumberInArray {
    static void frequencyNumber(int arr[], int size)
    {
        // Creating a HashMap containing integer
        // as a key and occurrences as a value
        HashMap freqMap
            = new HashMap();
 
        for (int i=0;i


Javascript


输出:
10 3
20 4
5 1

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

一个有效的解决方案是使用散列。

C++

// CPP program to count frequencies of array items
#include 
using namespace std;
 
void countFreq(int arr[], int n)
{
    unordered_map mp;
 
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Traverse through map and print frequencies
    for (auto x : mp)
        cout << x.first << " " << x.second << endl;
}
 
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}

Java

// Java program to count frequencies of array items
import java.util.*;
 
class GFG
{
 
    static void countFreq(int arr[], int n)
    {
        Map mp = new HashMap<>();
 
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
            if (mp.containsKey(arr[i]))
            {
                mp.put(arr[i], mp.get(arr[i]) + 1);
            }
            else
            {
                mp.put(arr[i], 1);
            }
        }
        // Traverse through map and print frequencies
        for (Map.Entry entry : mp.entrySet())
        {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.length;
        countFreq(arr, n);
    }
}
 
// This code contributed by Rajput-Ji

蟒蛇3

# Python3 program to count frequencies
# of array items
def countFreq(arr, n):
 
    mp = dict()
 
    # Traverse through array elements
    # and count frequencies
    for i in range(n):
        if arr[i] in mp.keys():
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
             
    # Traverse through map and print
    # frequencies
    for x in mp:
        print(x, " ", mp[x])
 
# Driver code
arr = [10, 20, 20, 10, 10, 20, 5, 20 ]
n = len(arr)
countFreq(arr, n)
 
# This code is contributed by
# Mohit kumar 29

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
    static void countFreq(int []arr, int n)
    {
        Dictionary mp = new Dictionary();
 
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
            if (mp.ContainsKey(arr[i]))
            {
                var val = mp[arr[i]];
                mp.Remove(arr[i]);
                mp.Add(arr[i], val + 1);
            }
            else
            {
                mp.Add(arr[i], 1);
            }
        }
         
        // Traverse through map and print frequencies
        foreach(KeyValuePair entry in mp)
        {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int []arr = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.Length;
        countFreq(arr, n);
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript


输出:
5 1
10 3
20 4

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

在上述有效的解决方案中,如何以与输入中出现的相同顺序打印元素?

C++

// CPP program to count frequencies of array items
#include 
using namespace std;
 
void countFreq(int arr[], int n)
{
    unordered_map mp;
 
    // Traverse through array elements and
    // count frequencies
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // To print elements according to first
    // occurrence, traverse array one more time
    // print frequencies of elements and mark
    // frequencies as -1 so that same element
    // is not printed multiple times.
    for (int i = 0; i < n; i++) {
      if (mp[arr[i]] != -1)
      {
          cout << arr[i] << " " << mp[arr[i]] << endl;
          mp[arr[i]] = -1;
      }
    }
}
 
int main()
{
    int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 };
    int n = sizeof(arr) / sizeof(arr[0]);
    countFreq(arr, n);
    return 0;
}

Java

// Java program to count frequencies of array items
import java.util.*;
 
class GFG
{
 
    static void countFreq(int arr[], int n)
    {
        Map mp = new HashMap<>();
 
        // Traverse through array elements and
        // count frequencies
        for (int i = 0; i < n; i++)
        {
            mp.put(arr[i], mp.get(arr[i]) == null ? 1 : mp.get(arr[i]) + 1);
        }
 
        // To print elements according to first
        // occurrence, traverse array one more time
        // print frequencies of elements and mark
        // frequencies as -1 so that same element
        // is not printed multiple times.
        for (int i = 0; i < n; i++)
        {
            if (mp.get(arr[i]) != -1)
            {
                System.out.println(arr[i] + " " + mp.get(arr[i]));
                mp.put(arr[i], -1);
            }
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.length;
        countFreq(arr, n);
    }
}
 
// This code contributed by Rajput-Ji

蟒蛇3

# Python3 program to count frequencies of array items
def countFreq(arr, n):
     
    mp = {}
     
    # Traverse through array elements and
    # count frequencies
    for i in range(n):
        if arr[i] not in mp:
            mp[arr[i]] = 0
        mp[arr[i]] += 1
         
    # To prelements according to first
    # occurrence, traverse array one more time
    # prfrequencies of elements and mark
    # frequencies as -1 so that same element
    # is not printed multiple times.
    for i in range(n):
        if (mp[arr[i]] != -1):
            print(arr[i],mp[arr[i]])
        mp[arr[i]] = -1
 
# Driver code
 
arr = [10, 20, 20, 10, 10, 20, 5, 20]
n = len(arr)
countFreq(arr, n)
 
# This code is contributed by shubhamsingh10

C#

// C# program to count frequencies of array items
using System;
using System.Collections.Generic;
 
class GFG
{
 
    static void countFreq(int []arr, int n)
    {
        Dictionary mp = new Dictionary();
 
        // Traverse through array elements and
        // count frequencies
         
        for (int i = 0 ; i < n; i++)
        {
            if(mp.ContainsKey(arr[i]))
            {
                var val = mp[arr[i]];
                mp.Remove(arr[i]);
                mp.Add(arr[i], val + 1);
            }
            else
            {
                mp.Add(arr[i], 1);
            }
        }
 
        // To print elements according to first
        // occurrence, traverse array one more time
        // print frequencies of elements and mark
        // frequencies as -1 so that same element
        // is not printed multiple times.
        for (int i = 0; i < n; i++)
        {
            if (mp.ContainsKey(arr[i]) && mp[arr[i]] != -1)
            {
                Console.WriteLine(arr[i] + " " + mp[arr[i]]);
                mp.Remove(arr[i]);
                mp.Add(arr[i], -1);
            }
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {10, 20, 20, 10, 10, 20, 5, 20};
        int n = arr.Length;
        countFreq(arr, n);
    }
}
 
// This code is contributed by Princi Singh

Javascript


输出:
10 3
20 4
5 1

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

这个问题可以在Java使用 Hashmap 解决。下面是程序。

Java

// Java program to count frequencies of
// integers in array using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfNumberInArray {
    static void frequencyNumber(int arr[], int size)
    {
        // Creating a HashMap containing integer
        // as a key and occurrences as a value
        HashMap freqMap
            = new HashMap();
 
        for (int i=0;i

Javascript


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