我试图仅打印数组中的重复元素以及每个元素出现的次数。
示例:
Number 0 appears 3 times;
Number 12 appears 2 times;
Number 43 appears 2 times
我的代码打印数组的所有元素,而不是仅打印重复的元素。
我必须提到我不能使用 HashMap
,仅conditional statments
.
谢谢
下面是代码:
int[] array = new int[] { 12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87 };
int counter = 0, temp = 0;// variable that holds the temporary value of each element
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
temp = array[i];
counter = 0;
for (int j = 0; j < array.length; j++) {
if (temp == array[j]) {
counter++;
}
}
System.out.println("Number:" + array[i] + "occurs :" + counter + " times");
}
最佳答案
您可以使用HashMap
或简单排序
,因为您的每个评论简单方法如下
int[] array = new int[]{12, 0, -22, 0, 43, 545, -4, -55, 12, 43, 0, -999, -87};
int counter = 0,
temp = 0;//variable that holds the temporary value of each element
Arrays.sort(array);
temp=array[0];
int count=1;
for(int i=1;i<array.length;i++)
{
//System.out.println(array[i]);
if(temp==array[i])
{
count++;
}
else
{
if(count==1)
{
count=1;
}
else{
System.out.println(array[i-1]+" "+count);
count=1;
}
temp=array[i];
}
}
关于java - 仅打印 int 数组中的重复项以及它们出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728027/