您的位置:首页 > 其它

Leetcode: Ugly Number II

2015-08-20 23:18 218 查看

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.

保存丑数序列,维护*2, *3 ,*5的三个队列,采用归并排序的思想选择最小的为下一个丑数。注意有可能某个丑数同时来自不同的队列。

class Solution {
public:
int nthUglyNumber(int n) {
vector<int> nums(n, 1);
int pos2 = 0, pos3 = 0, pos5 = 0;
for (int i = 1; i < n; ++i) {
nums[i] = min(min(nums[pos2] * 2, nums[pos3] * 3), nums[pos5] * 5);
if (nums[i] == nums[pos2] * 2) {
++pos2;
}
if (nums[i] == nums[pos3] * 3) {
++pos3;
}
if (nums[i] == nums[pos5] * 5) {
++pos5;
}
}

return nums[n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 丑数