public static int countRepeats(int[] items) {
int l=items.length;
int num=0;
int[] count=new int[l];
for(int i=0;i<l;i++){
for(int j=i+1;j<l;j++){
if(items[i]==items[j]){
count[i]++;
}
}
}
for(int i=0;i<l;i++){
if(count[i]>0){
num++;
}
}
return num;
}
// {1,2,1,3,4,5,5}应该给2; 2个数字重复 // {0,0,0}但是我的代码为这个代码提供了2 ..
答案 0 :(得分:1)
从你的代码,数组{0, 0, 0}
,第一个元素将被计为2,第二个元素将被计为1,然后最后一个将被计为0,当然,它给你2。试试这个:
public static int countRepeats(int[] items) {
int num = 0;
Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
for (Integer i : items) {
if (countMap.containsKey(i)) { // check if map does contain the key or not, if does, make this key'value +1;
countMap.put(i, countMap.get(i) + 1);
} else { // if not contain the key, just put it as a new key and the value is 1.
countMap.put(i, 1);
}
}
for (Integer item : countMap.values()) {
if (item > 1) {
num++;
}
}
return num;
}
使用Map
存储数字的显示次数,然后获取此地图中的所有值,计算超过1的值,然后就可以得到你想要的数据。
答案 1 :(得分:1)
您的算法不正确。不确定你的输入,但如果所有数字都是正数且不是很大(不足以担心内存),你可以试试这个。它可以处理任意数量的重复。
public static int countRepeats(int[] items) {
int l=items.length;
int num=0;
int max=0;
for(int i=0;i<l;i++){
if(items[i] > max) max = items[i]; // get the largest number
}
int[] count=new int[max + 1]; // assume count elements are initiated with 0
for(int i=0;i<l;i++){
count[items[i]]++;
}
for(int i=0;i<=max;i++){
if(count[i]>1){
num++;
}
}
return num;
}
答案 2 :(得分:1)
仅设置存储不同的项目。您可以使用一组来查找重复项,另一组用于清楚地存储它们,然后返回后一组的大小:
public static int countRepeats(int[] items) {
Set<Integer> distinct = new HashSet<>();
Set<Integer> duplicate = new HashSet<>();
for (int item : items) {
if (!distinct.add(item)) {
// item was already contained in set
duplicate.add(item);
}
}
return duplicate.size();
}
答案 3 :(得分:0)
地图可能会有所帮助,就像:
public static int countRepeats(int[] items) {
int res = 0;
Map<Integer,Integer> map = new HashMap<>();
for(int i:items){
map.put(i, map.get(i)==null?0:map.get(i)+1);
}
for(Integer key:map.keySet()){
if(map.get(key)>0){
res++;
}
}
return res;
}