在原始的Java数组检测重复的值 [英] Detect duplicate values in primitive Java array

查看:94
本文介绍了在原始的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?

推荐答案

我将有一个地图<整数,整数GT; 其中,第一个整数是值是计数(发生数)。

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(数组[I])。如果在地图中存在一个数字,增加这个数字(类似 map.put(数组[我],map.get(数组[I])+ 1)。否则,创建一个地图(如 map.put(数组[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 like map.put(array[i], map.get(array[i]) + 1). Otherwise, create a new entry in a map (e.g map.put(array[i], 1).
  • Finally, iterate through the map and retrieve all keys where value is greater than 1.

这篇关于在原始的Java数组检测重复的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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