检测原始 Java 数组中的重复值 [英] Detect duplicate values in primitive Java array
本文介绍了检测原始 Java 数组中的重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检测 Java 数组中的重复值.例如:
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?
推荐答案
我将有一个 Map
其中第一个整数是 value
数组中出现的数字和第二个整数是 count
(出现次数).
I'll have a Map<Integer, Integer>
where the first integer is the value
of the number that occurs in the array and the second integer is the count
(number of occurrence).
- 循环遍历
array.length
- 对于数组中的每一项,执行一个
map.containsKey(array[i])
.如果地图中存在数字,则增加该数字(类似于map.put(array[i], map.get(array[i]) + 1)
.否则,创建一个新条目在地图中(例如map.put(array[i], 1)
. - 最后,遍历映射并检索值大于 1 的所有键.
- Run through the
array.length
in a loop - for each item in the array, do a
map.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)
. - Finally, iterate through the map and retrieve all keys where value is greater than 1.
这篇关于检测原始 Java 数组中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文