自己写的超时版本,每次计算没有用到之前的计算结果。
public int nthUglyNumber(int n) {
if (n == 1) return 1;
int[] arr = new int[n];
arr[0] = 1;
int index = 1;
int num = 2;
while (index < n){
if (isUgly(num)){
arr[index++] = num;
}
num++;
}
return arr[n - 1];
}
private boolean isUgly(int n) {
while (n != 1){
if (n % 2 == 0){
n /= 2;
} else if (n % 3 == 0){
n /= 3;
} else if (n % 5 == 0){
n /= 5;
} else {
break;
}
}
return n == 1;
}
自己模仿题解写的,while循环会增加很多不必要的判断导致代码的效率降低。
public int nthUglyNumber1(int n) {
int[] res = new int[n];
res[0] = 1;
int indexA = 0;
int indexB = 0;
int indexC = 0;
int count = 0;
int tempA = 0, tempB = 0,tempC = 0;
while (count < n - 1){
if ((tempA = res[indexA] * 2) <= res[count]) indexA++;
else if ((tempB = res[indexB] * 3) <= res[count]) indexB++;
else if ((tempC = res[indexC] * 5) <= res[count]) indexC++;
else {
res[++count] = Math.min(Math.min(tempA,tempB),tempC);
}
}
return res[n - 1];
}
优秀的写法,少判断了很多次。
public int nthUglyNumber2(int n) {
int[] res = new int[n];
res[0] = 1;
int indexA = 0;
int indexB = 0;
int indexC = 0;
for (int i = 1; i < n; i++) {
int tempA = 2 * res[indexA], tempB = 3 * res[indexB],tempC = 5 * res[indexC];
res[i] = Math.min(Math.min(tempA,tempB),tempC);
if (tempA == res[i]) indexA++;
if (tempB == res[i]) indexB++;
if (tempC == res[i]) indexC++;
}
return res[n - 1];
}