问题描述:
设计一个算法,找出只含素因子2
,3
,5
的第 n 小的数。
符合条件的数如:1, 2, 3, 4, 5, 6, 8, 9, 10, 12...
如果n = 9
, 返回 10
Ugly Number: 1, 2, 3, 4, 5, 6, 8, 10, ..........
那么 1*2 2*2 3*2 4*2 5*2 6*2 8*2 10*2 ...........*2
1*3 2*3 3*3 4*3 5*3 6*3 8*3 10*3 .......... *3
1*5 2*5 3*5 4*5 5*5 6*5 8*5 10*5 .......... *5
可以很清晰的看出来,如果用p2, p3, p5三个指针分别用来指向下面三行中的过程,逐渐移动着三个指针,注意,一旦找到第一个大于结果数组的lastNumber就停止该指针向后移动,然后将三个中较小的加入到结果数组中。代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int nthUglyNumber(int n) {
// write your code here
vector<int> nums;
nums.push_back(1);
int p2 = 0, p3 = 0, p5 = 0;
for (int i = 1; i < n; i++)
{
int lastNumber = nums[i - 1];
cout << "last number : " << lastNumber << endl;
while (nums[p2] * 2 <= lastNumber)
p2++;
while (nums[p3] * 3 <= lastNumber)
p3++;
while (nums[p5] * 5 <= lastNumber)
p5++;
nums.push_back(min(min(nums[p2] * 2, nums[p3] * 3), nums[p5] * 5));
}
return nums[n - 1];
}
int main()
{
cout << nthUglyNumber(15) << endl;
system("pause");
return 0;
}
这一题总结下心得吧,遇到问题应该多思考,画出来,找找规律,就能发现不一样的方法。