题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
Example:
Input: n = 10 Output: 12 Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
class Solution {
public:
int minThree(int a, int b, int c)
{
return a<b?min(a,c):min(b,c);
}
int GetUglyNumber_Solution(int index) {
int pos=0,pos1=0,pos2=0;
vector<int> ans;
ans.push_back(1);
while(ans.size()<index)
{
int flag = minThree(2*ans[pos],3*ans[pos1],5*ans[pos2]);
ans.push_back(flag);
if(flag == 2*ans[pos])
pos++;
if(flag==3*ans[pos1])
pos1++;
if(flag==5*ans[pos1])
pos2++;
}
return ans[index-1];
}
};