前言
丑数2题目的动态规划真是惊到我,原来这是动态规划?使用三个指针i2,i3,i5。计算num[i2]*2,nums[i3]*3,nums[i5]*5,得到最小值加入到nums中,取得的最小值指针往前一位,由于数目有1690个,所有采用一个类预计算,(假装时间复杂度真的只有O(1)哈哈哈哈)
题目
源码
丑数1
class Solution:
def isUgly(self, num: int) -> bool:
if num<1:
return False
while num%2==0:
num=num//2
while num%3==0:
num=num//3
while num%5==0:
num=num//5
return num==1
class Solution {
public boolean isUgly(int num) {
if (num<1){
return false;
}
while (num%2==0){
num /=2;
}while(num%3==0){
num/=3;
}while(num%5==0){
num/=5;
}
return num==1;
}
}
丑数2
class Ugly{
public int[] nums=new int[1690];
Ugly(){
nums[0]=1;
int i2=0,i3=0,i5=0,ugly;
for(int i =1;i<1690;++i){
ugly=Math.min(Math.min(nums[i2]*2,nums[i3]*3),nums[i5]*5);
nums[i]=ugly;
if (ugly == nums[i2]*2) ++i2;
if(ugly == nums[i3]*3) ++i3;
if (ugly == nums[i5]*5) ++i5;
}
}
}
class Solution {
public static Ugly u = new Ugly();
public int nthUglyNumber(int n) {
return u.nums[n-1];
}
}
class Ugly():
def __init__(self):
self.nums=nums=[1,]
i2=i3=i5=0
for i in range(1,1690):
ugly =min(nums[i2]*2,nums[i3]*3,nums[i5]*5)
nums.append(ugly)
if nums[i2]*2==ugly:
i2+=1
if nums[i3]*3==ugly:
i3+=1
if nums[i5]*5==ugly:
i5+=1
class Solution:
u=Ugly()
def nthUglyNumber(self, n: int) -> int:
return self.u.nums[n-1]