题目描述
把只包含质因子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, 12is the sequence of the first10ugly 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];
}
};

本文介绍了一种求解第N个丑数的方法,丑数是仅包含质因子2、3和5的正整数。通过一个高效的算法,我们可以在O(N)的时间复杂度内找到所需的丑数。示例中,输入n=10,输出为12,解释了从1开始的前10个丑数序列。
720

被折叠的 条评论
为什么被折叠?



