数组中的最常用的值 [英] Most common values in an array

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

问题描述

我将如何去在一个数组寻找三种最常见的元素呢?我与长度10,000元素的数组工作从0-100 =随机整数。

How would I go about finding the three most common elements in an array? I am working with an array of length 10,000 with elements = random integer from 0-100.

我想用两个数组,长度为100的一个,只是由if语句使用递增。不过,我想知道是否有一种方法,只有一个用于/如果环(声明)可以用来找到这些值。

I was thinking of using two arrays, one of length 100 and just incrementing by using an if statement. However, I was wondering if there is a way that only one for/if loop(statement) could be used to find these values.

推荐答案

如果你要做到这一点的一个常数越过列表,你需要第二个数据结构。

If you are going to do this in a constant number of passes over the list, you need a second data structure.

如果您在该集合中的值的下限和上限,值是相对密集,则计数器阵列是一个很好的解决方案。

If you have lower and upper bounds for the values in that set and the values are relatively dense, then an array of counters is a good solution.

否则的话,最好使用地图<整数,整数方式> ,其中键是集的元素和值计数器

Otherwise, it is better to use a Map<Integer, Integer>, where the keys are elements of the set and the values are counters.

分析

如果你没有在设定的下限/上限在开始之前,你不知道大柜分配的数组。所以,你必须做出一个preliminary通过阵列上找到的界限......你现在有一个二传的解决方案。

If you don't have lower / upper bounds on the set before you start, then you don't know big an array of counters to allocate. So you have to make a preliminary pass over the array to find the bounds ... and you now have a two pass solution.

如果你有下限和上限,但该组稀疏,则初始化计数阵列的成本+找到三个最大计数将主导计数组元件的成本的成本。如果差异足够大(即输入大和放大器;非常稀疏)。一个HashMap会更快,并会采取更少的内存

If you do have lower and upper bounds but the set is sparse, then the cost of initializing the array of counts + the cost of finding the three largest counts will dominate the cost of counting the set elements. If the difference is large enough (i.e. the input is large & very sparse) a HashMap will be faster and will take less memory.

或者

如果您被允许更改阵列,可以把它的升序排列 O(NlogN),然后找到在单传过来的三个最常见的元素排序的数组。

If you are allowed to change the array, you can sort it into ascending order O(NlogN) and then find the three most common elements in a single pass over the sorted array.

这篇关于数组中的最常用的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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