这里我有一个简单的方法,可以使用哈希图查找所有重复的数字。这仅显示重复的数字,我还需要计算每个数字的出现次数。如何实现我的 for 循环来计算每个数字的频率?
//司机
public class findDuplicates{
public static void main(String[] args){
int [] input = {2,3,6,5,5,6,9,8,7,7,7,4,1,2,5,5,2};
dulicates(input);
}
public static void dulicates(int[] MyArray){
Map<Integer,Integer> HashMap = new HashMap<Integer, Integer>();
for (int i : MyArray){
if(!HashMap.containsKey(i)){
HashMap.put(i, 1);
}else{
HashMap.put(i, HashMap.get(i)+1);
}
}
for (Integer i : HashMap.keySet()){
System.out.println("This has a duplicate: " + i );
}
}
}
}
答案 0 :(得分:4)
您已经解决了,只是错过了迭代并检查了 > 0 的值。
for(Map.Entry<Integer,Integer> kv : map.entrySet())
{
if (kv.getValue()>0)
System.out.println(kv.getKey()+" has "+ kv.getValue() +" duplicate(s)");
}
基于这个逻辑,考虑为你的压缩字符串实现一个 getter 方法。
此处的示例,使用仅包含重复项(只是为了好玩)的 map
和可以帮助您识别重复项和存储唯一项的单个 set
。多亏了这一点,您可以从基本数组中返回一个没有重复项的 int[]
。
static int[] showDuplicatesAndGetCleanArray(int[] myArray) //pls change my name
{
//myArray = {2,3,6,5,5,6,9,8,7,7,7,4,1,2,5,5,2};
Set<Integer> uniques = new HashSet<>(myArray.length);
Map<Integer,Integer> dupMap = new HashMap<>(myArray.length);
for (int i : myArray)
{
if(uniques.contains(i))
dupMap.put(i, dupMap.get(i)==null ? 1 : dupMap.get(i)+1);
else
uniques.add(i); //else not required, I love useless micro-optimizations
}
System.out.println("Total duplicates : [" + (myArray.length-uniques.size())+"]");
for(Map.Entry<Integer,Integer> kv : dupMap.entrySet())
System.out.println("- {" + kv.getKey() + "} has " + kv.getValue() +
" duplicate" + (kv.getValue()>1 ? "s" : "") );
return uniques.stream().mapToInt(Integer::intValue).toArray();
}
结果:
Total duplicates : [8]
- {2} has 2 duplicates
- {5} has 3 duplicates
- {6} has 1 duplicate
- {7} has 2 duplicates
/* returned int[] => {1,2,3,4,5,6,7,8,9} */
答案 1 :(得分:2)
Map
接口中有一些方法可以简化此操作。一个是 compute()
。
compute(i, (k,v)-> v == null ? 1 : v + 1
表示如果 value
的 key
是 null
,初始化为 1
,否则,添加 {{ 1}} 到现有的 1
。value
印刷品
public static void main(String[] args) {
int [] input = {2,3,6,5,5,6,9,8,7,7,7,4,1,2,5,5,2};
duplicates(input);
}
public static void duplicates(int[] myArray){
Map<Integer,Integer> freq = new HashMap<>();
// perform a frequency count of the array
for (int i : myArray) {
freq.compute(i, (k,v)-> v == null ? 1 : v + 1);
}
// now just print the duplicates and their count.
System.out.println("Duplicates");
freq.forEach((k,v) -> {
if (v > 1) {
System.out.printf("%s occurs %s times.%n", k,v);
}
});
}
答案 2 :(得分:0)
因为我觉得这可能是一个家庭作业,你应该自己做一些计算,所以我会给出基本的想法而不是代码。这就是你要弄清楚的。
哈希图允许您使用键来访问值。所以对于在输入中找到的每个唯一值。
检查 hashmap 中是否有具有该键的元素,如果没有,则在 hashmap 中放置一个新元素,以找到的值作为其键,并将 1 作为其值。
否则,如果 hashmap 中存在具有该键的项目,则将值拉出,递增并放回该键下。
通过返回哈希图结束您的函数。