如何计算java中数组中的重复元素

Semiron:

我有一个整数数组,例如= 3,1,2,3,1; 我只想计算此数组有多少重复项。例如,此数组现在有4个重复项。输入是数组,输出将是重复元素的数量。是否有任何方法或类?你能帮我实现我自己的吗?注意:我不是在寻找指定元素的出现次数。我只想知道此数组有多少个重复项。例如,我说它对于提到的数组有4个重复项。其中2个为“ 3”,其中2个为“ 1”!

Gtomika:

好吧,一张地图可以用来存储数字以及它们出现的次数:

Map<Integer,Integer> map = new HashMap<>();
for(int i: numbers) { //suppose you have the numbers in 'numbers' array
   if(map.containsKey(i) { //this number is in the map already
      map.put(i, map.get(i)+1);
   } else { //we didnt see this number before
      map.put(i, 1);
   }
}

//now we loop the map to sum the repeating numbers
int sum = 0;
for(int amount: map.values()) {
   if(amount > 1) sum += amount;
}

此方法的优点是您可以确切知道数组中每个数字有多少个。您稍后可能需要该信息。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章