检测原始 Java 数组中的重复值
我想检测 Java 数组中的重复值。例如:
int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
如何获取特定的重复条目以及它出现的次数?
I want to detect duplicate values in a Java array. For example:
int[] array = { 3, 3, 3, 1, 5, 8, 11, 4, 5 };
How could I get the specific duplicated entry and how many times it occurs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我将有一个
Map
,其中第一个整数是数组中出现的数字的value
,第二个整数是count
(出现次数)。array.length
map.containsKey(array[i])
。如果映射中存在数字,则增加该数字(类似于map.put(array[i], map.get(array[i]) + 1)
。否则,创建一个新条目在映射中(例如map.put(array[i], 1)
)。I'll have a
Map<Integer, Integer>
where the first integer is thevalue
of the number that occurs in the array and the second integer is thecount
(number of occurrence).array.length
in a loopmap.containsKey(array[i])
. If there exists a number in a map, increment that number (something likemap.put(array[i], map.get(array[i]) + 1)
. Otherwise, create a new entry in a map (e.gmap.put(array[i], 1)
.看起来像是一个名为
multiset
的数据结构工作。标准 JDK 6 是原始的,不包含
multiset
。如果您不想重写它,您可以使用预先存在的库,例如 Google Guava-libraries 或 Apache Commons。例如,使用 Guava-libraries,您可以
输出:
Seems like a job for data structure called
multiset
.Standard JDK 6 is primitive and do not contain
multiset
. If you do not want to rewrite it, you can use preexisting library like Google Guava-libraries or Apache Commons.For example with Guava-libraries you can
And this would output:
答案取决于源数组中的数字范围。如果范围足够小,您可以分配一个数组,循环遍历源并在源编号的索引处递增:
如果源数组包含未知或太大的范围,您可以创建一个
Map
并算在内:注意。在没有 JVM 帮助的情况下输入上述内容,剩下的就是消除拼写错误
作为读者的练习:-)
The answer depends on the number range in your source array. If the range is small enough you can allocate an array, loop through your source and increment at the index of your source number:
If your source array contains an unknown or too large range, you can create a
Map
and count in that:NB. typed the above without the help of a JVM, getting rid of typoes is left
as an exercise for the reader :-)
您可以使用 Collectors.frecuency() 和 Collectors.groupingBy。
这就是我的做法,希望这可以帮助你。
输出是:
您甚至可以使用频率删除所有不重复的数字:
Map FinalValues = new HashMap();
输出是:
You can use Collectors.frecuency() and Collectors.groupingBy.
This is how i do this, hope this can help you.
The output is:
You can even use frecuency to delete all the numbers that doesn't repeat:
Map finalValues = new HashMap();
The output is :
为第一步分配一个计数器,然后您可以将它们与另一个数组相关联,将每个数字分配给一个索引,然后如果您的数字重复,则增加您的计数器...
assign a counter for the first step then you can relate them to an another array assigning each number to an index then if your number is duplicated increment your counter...
对数组进行排序,然后扫描它或 Arrays.binarySearch + 沿任一方向扫描。由于分配量少得多并且没有包装,因此速度会更快,尤其是在较大的数组上。
Sort the array, then either scan it or
Arrays.binarySearch
+ scan in either direction. Due to much fewer allocations and no wrapping, this can be faster, especially on larger arrays.