查找给定数字组中的数字的频率 [英] Finding Frequency of numbers in a given group of numbers

查看:123
本文介绍了查找给定数字组中的数字的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个C ++中的向量/数组,我们希望计算这些N个元素中的哪一个具有最大重复出现次数,并输出最高计数。



示例:

  int a = {2,456,34,3456,2,435,2,456,2} 

输出为4,因为2发生4次。

解决方案

排序数组,然后快速通过计数每个数字。该算法具有O(N * logN)复杂性。



或者,使用数字作为键来创建哈希表。在哈希表中存储你键入的每个元素的计数器。你可以在一个通过计数所有元素;然而,算法的复杂性现在取决于您的hasing函数的复杂性。


Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.

example:

int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}

the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.

解决方案

Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity.

Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function.

这篇关于查找给定数字组中的数字的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆