Mah*_*ddy 3 java algorithm complexity-theory
我写的示例代码.但这是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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是伪代码的解决方案:
Map<Int, Int> histogram;
for(number in array) {
histogram[number]++;
}
Run Code Online (Sandbox Code Playgroud)
现在histogram[somenumber]包含数字在数组中的次数 - O(n)假设Map查找项目O(1)
选项1:牺牲记忆速度.
HashMap来记录每个数字的频率.选项2:排序