思路分析
首先需要丑数的递推性质
暴力
判断每个数是不是只能被2,3,5整除
cpp
class Solution {
public:
bool check(int n){
while(n%2==0)n/=2;
while(n%3==0)n/=3;
while(n%5==0)n/=5;
return n==1?true:false;
}
int nthUglyNumber(int n) {
int cnt = 0;
for(int i=1;;i++){
if(check(i))cnt++;
if(n==cnt)return i;
}
}
};
python
class Solution:
def check(self,n:int) -> bool:
while n%2==0:n//=2
while n%3==0:n//=3
while n%5==0:n//=5
return True if n==1 else False
def nthUglyNumber(self, n: int) -> int:
cnt,i = 0,1
while cnt!=n:
if self.check(i):cnt+=1
i += 1
return i-1
小根堆
将所有的丑数的存在一个nums
中,然后每次使用
cpp
class Solution {
public:
typedef long long II;
int nthUglyNumber(int n) {
vector<II> nums;
nums.push_back(1); // 初始只有1
priority_queue<II,vector<II>,greater<II>> q;
while(nums.size()<n){
II cur = nums.back(); // 每次取最后一个数
// 每次会产生3个新数字
q.push(cur *2);
q.push(cur *3);
q.push(cur *5);
while(q.top() == cur)q.pop();
// 每次加完就是删除
nums.push_back(q.top()),q.pop();
}
return nums[n-1];
}
};
python
class Solution:
import heapq
def nthUglyNumber(self, n: int) -> int:
nums = [1]
q = []
heapq.heapify(q) # 队列化
while len(nums)<n:
cur = nums[-1]
heapq.heappush(q,2*cur)
heapq.heappush(q,3*cur)
heapq.heappush(q,5*cur)
while q[0]==cur: heapq.heappop(q)
nums.append(q[0])
heapq.heappop(q)
return nums[n-1]
三路归并
nums: 丑数序列
nums[i]: 因数为2的丑数
nums[j]: 因数为3的丑数
nums[k]: 因数为5的丑数
cpp
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> nums;
nums.push_back(1);
int i=0,j=0,k=0;
while(nums.size()<n){
int t = min(nums[i]*2,min(nums[j]*3,nums[k]*5));
nums.push_back(t);
if(t==nums[i]*2)i++;
if(t==nums[j]*3)j++;
if(t==nums[k]*5)k++;
}
return nums[n-1];
}
};
python
class Solution:
def nthUglyNumber(self, n: int) -> int:
nums = [1]
i,j,k = 0,0,0
while len(nums)<n:
t = min(nums[i]*2,min(nums[j]*3,nums[k]*5))
nums.append(t)
if t == nums[i]*2:i+=1
if t == nums[j]*3:j+=1
if t == nums[k]*5:k+=1
return nums[n-1]