有什么方法可以避免 java 中的嵌套 "for" 循环
Is there any way to avoid nested "for" loops in java
所以我正在解决一个编码挑战,但由于超时,我的代码在具有大量输入的测试用例中失败了。
我需要模拟 "count" 次。
每次模拟都会产生一个介于 0 到 364 之间的随机数 "size" 次
如果两个数字存储在同一个索引中,这意味着计数为“2”,则应存储和计算每个数字,然后 Hits++
return 相对于 "count"
的命中百分比
public double calculate(int size, int count) {
// TODO -- add your code here
int Hits=0;
for(int j=1;j<=count;j++) { // number of simulation
int BirthDays[]=new int[365];
Random rnd = new Random();
rnd.setSeed(j);
for(int i=0;i<size;i++){ //number of people
int x=rnd.nextInt(365);
BirthDays[x]=BirthDays[x]+1;
if(BirthDays[x]>=2){
Hits++;
break;
}
}
}
return(((float)Hits/count)*100);
}
那么有什么办法可以降低时间复杂度吗?
数据结构可以改变它不是数组独有的。
我立即看到的最节省时间的方法是将 Random rnd = new Random()
移出循环。您不需要每次都创建一个新实例,而且速度很慢。
public double calculate(int size, int count) {
int max = 365;
int birthDays[] = new int[max];
Random rnd = new Random();
int hits = 0;
for(int j = 1; j <= count; j++) {
Arrays.fill(birthDays, 0);
rnd.setSeed(j);
for(int i = 0; i < size; i++) {
int x = rnd.nextInt(max);
birthDays[x]++;
if(birthDays[x] >=2 ) {
hits++;
break;
}
}
}
return (hits/count) * 100;
}
所以我正在解决一个编码挑战,但由于超时,我的代码在具有大量输入的测试用例中失败了。
我需要模拟 "count" 次。 每次模拟都会产生一个介于 0 到 364 之间的随机数 "size" 次 如果两个数字存储在同一个索引中,这意味着计数为“2”,则应存储和计算每个数字,然后 Hits++ return 相对于 "count"
的命中百分比public double calculate(int size, int count) {
// TODO -- add your code here
int Hits=0;
for(int j=1;j<=count;j++) { // number of simulation
int BirthDays[]=new int[365];
Random rnd = new Random();
rnd.setSeed(j);
for(int i=0;i<size;i++){ //number of people
int x=rnd.nextInt(365);
BirthDays[x]=BirthDays[x]+1;
if(BirthDays[x]>=2){
Hits++;
break;
}
}
}
return(((float)Hits/count)*100);
}
那么有什么办法可以降低时间复杂度吗? 数据结构可以改变它不是数组独有的。
我立即看到的最节省时间的方法是将 Random rnd = new Random()
移出循环。您不需要每次都创建一个新实例,而且速度很慢。
public double calculate(int size, int count) {
int max = 365;
int birthDays[] = new int[max];
Random rnd = new Random();
int hits = 0;
for(int j = 1; j <= count; j++) {
Arrays.fill(birthDays, 0);
rnd.setSeed(j);
for(int i = 0; i < size; i++) {
int x = rnd.nextInt(max);
birthDays[x]++;
if(birthDays[x] >=2 ) {
hits++;
break;
}
}
}
return (hits/count) * 100;
}