Java – find the number of repetitions of a number in an array less than o (n ^ 2)
•
Java
I wrote the sample code But this is n ^ 2
int a[]={1,4,1,5,2,3,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");
}
}
Solution
This is the pseudo code solution:
Map<Int,Int> histogram;
for(number in array) {
histogram[number]++;
}
Now histogram [somenumber] contains the number of times a number is in the array – in O (n), suppose map finds an item in O (1)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
