1.暴力
暴力就是从1开始循环然后判断是不是丑数。数据量大的时候直接超时,不过逻辑是正确的,过掉94%
public class Main {
//是不是丑数
public boolean isUgly(int n) {
boolean result = false;
if (n == 1) {
return !result;
}
if (isOk(n)) {
while (n % 2 == 0) {
n = n >>1;
}
while (n % 3 == 0) {
n = n / 3;
}
while (n % 5 == 0) {
n = n / 5;
}
if (n == 1) {
result = true;
}
}
return result;
}
public boolean isOk(int n) {
boolean result = false;
if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0) {
result = true;
}
return result;
}
public int nthUglyNumber(int n) {
int counter = 0;
int result = 0;
for (int i = 1; ; i++) {
if (isUgly(i)) {
counter++;
}
if (counter == n) {
result = i;
break;
}
}
return result;
}
public static void main(String[] args) {
Main main = new Main();
System.out.println(main.nthUglyNumber(41));
}
}
2.合成
我们可以直接从要求入手单手合成丑数,然后根据我们操作的次数来结束战斗。思路就是要找到最接近前一个数的值,然后分别*2,*3,*5再来取得最小值就是结果了。参考九章算数
import java.util.*;
import java.lang.*;
public class Solution {
public int nthUglyNumber(int n) {
int p2 = 0;
int p3 = 0;
int p5 = 0;
List<Integer> ugly = new ArrayList<>();
ugly.add(1);
for (int i = 1; i < n; i++) {
int temp = ugly.get(i - 1);
while (ugly.get(p2) * 2 <= temp) {
p2++;
}
while (ugly.get(p3) * 3 <= temp) {
p3++;
}
while (ugly.get(p5)*5 <= temp) {
p5++;
}
ugly.add(Math.min(Math.min(ugly.get(p2)*2,ugly.get(p3)*3),ugly.get(p5)*5));
}
return ugly.get(n-1);
}
}