Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number.
Difficulty: Medium
三个sorted list, 分别*2 *3 *5 比较,巧妙的方法
class Solution {
public:
int nthUglyNumber(int n) {
int m_2 = 0, m_3 = 0, m_5 = 0;
vector<int> nums;
nums.push_back(1);
while(nums.size() < n){
if(nums[m_2] *2 <= nums[m_3]*3 && nums[m_2] *2 <= nums[m_5]*5){
nums.push_back(nums[m_2]*2);
m_2++;
}
else if(nums[m_3] *3 <= nums[m_2]*2 && nums[m_3] *3 <= nums[m_5]*5){
nums.push_back(nums[m_3]*3);
m_3++;
}
else{
nums.push_back(nums[m_5]*5);
m_5++;
}
if(nums[nums.size() - 1] == nums[nums.size() - 2])
nums.pop_back();
}
return nums[n-1];
}
};