方法1:从头遍历找到第n个,但是会超时的,判断丑数的方法就是,把是2的因子全部去掉,把含5的因子全部去掉,把3的因子全部去掉,看是否是1.
class Solution {
public int nthUglyNumber(int n) {
int count=1;
int i=1;
while(count<n){
i++;
if(ischou(i)) count++;
}
return i;
}
public boolean ischou(int n){
while(n!=0&&n%2==0) n=n/2;
while(n!=0&&n%3==0) n=n/3;
while(n!=0&&n%5==0) n=n/5;
return n==1;
}
}
方法2:使用i2,i3,i5三个指针,分别表示乘以2,3,5的位置,开始都指向1位置,然后找三个指针乘以对应数的最小值,即2放在第二个位置,然后看哪个指针乘以对应数等于2,如果等于,将指针位置+1,因为当前不可能再用到他了,他已经出现了,只能放大(即往后移动),这可不是一次只移动一个指针哦,有可能移动两个指针的,三个也可能,只要当前指针乘以对应的数出现了,就必须向下移动一个位置。
class Solution {
public int nthUglyNumber(int n) {
int i2=1,i3=1,i5=1,count=1;;
int[] help=new int[n+1];
help[1]=1;
while(count<n){
help[++count]=Math.min(help[i2]*2,Math.min(help[i3]*3,help[i5]*5));
if(help[i2]*2==help[count]) i2++;
if(help[i3]*3==help[count]) i3++;
if(help[i5]*5==help[count]) i5++;
}
return help[n];
}
}
总结:对于求数列的第几项的问题,都可以这么考虑,就是当前项由前面哪几项影响,得到
1201丑数三
这个方法超时了,这不是就是3n的时间复杂度吗??怎么又卡常数啊,烦
class Solution {
public int nthUglyNumber(int n, int a, int b, int c) {
int count=1;
int i=2;
while(count<n){
if(++i%a==0||i%b==0||i%c==0) count++;
}
return i;
}
}
这个题我不知道为啥,我这么做就是错,能过很多case的
class Solution {
public int nthUglyNumber(int n, int a, int b, int c) {
int count=0;
int ia=1,ib=1,ic=1,res=0;
while(count<n){
res=Math.min(ia*a,Math.min(ib*b,ic*c));
if(res==ia*a) ia++;
if(res==ib*b) ib++;
if(res==ic*c) ic++;
count++;
}
return res;
}
}