我使用下面的代码,但输出不正确
// 1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4 ,7,7,5,2,1,3,4,6,311,1
public static void repeat(){
int count[] = new int[]{1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
int [] done ;
for(int i = 0; i < count.length; i++) {
int a = count[i] ;
int counter=0;
int j=i+1;
//System.out.println(a+"--"+""+j);
for(j=i+1 ; j < count.length; j++){
if (a == count[j]) {
counter=counter+1;
}
System.out.println(a+" is appearing --"+""+counter +" times");
}
}
}
答案 0 :(得分:0)
尝试创建一个键类型为Integer且值相同的Map。然后遍历count数组 - 检查map中是否存在给定值 - 如果没有将其添加为值为1的键,如果它确实存在,则只需将该值增加1.
在此之后浏览地图并获取值为&gt;的所有键。 1。
public static void repeat(){
int count[] = new int[] {1,3,4,5,6,3,2,4,6,7,9,4,12,3,4,6,8,9,7,6,43,2,4,7,7,5,2,1,3,4,6,311,1};
Map<Integer,Integer> repetitionCount = new HashMap<>();
for(Integer i : count) {
if(repetitionCount.containsKey(i)) {
Integer prevValue = repetitionCount.get(i);
repetitionCount.put(i,prevValue+1);
} else {
repetitionCount.put(i,1);
}
}
repetitionCount.forEach((key,value) -> {
if(value>1) {
System.out.println("Repetition of " + key + " - " + value + " times");
}
}
);
}