我写的示例代码。但这是 n^2
int a[]={1,4,1,5,2,2,4,3,4,1};
int b[][]=new int[5][2];
int i,j,k=0,count=1;
boolean temp=false;
for(i=0;i<a.length;i++)
{
for(j=0;j<5;j++)
{
if(a[i]==b[j][0])
{ temp=true;
b[j][1]++;
break;
}
}
if(temp==false)
{
b[k][0]=a[i];
b[k][1]=1;
k++;
}
temp=false;
}
for(i=0;i<5;i++)
{
for(j=0;j<1;j++)
{
System.out.println(b[i][j]+" is repeated "+b[i][j+1]+" times");
}
}
最佳答案
这是伪代码的解决方案:
Map<Int, Int> histogram;
for(number in array) {
histogram[number]++;
}
现在 histogram[somenumber]
包含数字在数组中的次数 - 在 O(n)
中假设 Map
看起来在 O(1)
关于java - 在小于 O(n^2) 的数组中查找数字重复的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5742551/