题意:把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
思路:暴力每个数,判断是不是丑数,直到找到第N个丑数。(这个有点慢,不考虑)
不能暴力所有数,我们考虑暴力丑数。
假设数组里面的最大丑数为number;
肯定存在一个T2,使得T2前面的所有丑数*2都小于number,T2后面的所有丑数*2都大于number。
同理T3,T5也存在;
那么每次我们往数组里面,添加丑数的时候,更新T2,T3,T5;
如何添加这个丑数呢?
因为要按顺序,那么应该是最小的(T2*2,T3*3,T5*5)
代码:
#include <iostream>
using namespace std;
class Solution {
public:
int min(int a, int b)
{
return a < b ? a : b;
}
int GetUglyNumber_Solution(int index) {
if (index <= 0) return 0;
//index = index - 1;
vector<int> pUglyNumbers(index);
pUglyNumbers[0] = 1;
int nextUglyIndex = 1;
int pMultiply2Pos = 0;
int pMultiply3Pos = 0;
int pMultiply5Pos = 0;
while (nextUglyIndex < index)
{
int number = min(min(pUglyNumbers[pMultiply2Pos] * 2, pUglyNumbers[pMultiply3Pos] * 3), pUglyNumbers[pMultiply5Pos] * 5);
pUglyNumbers[nextUglyIndex] = number;
while (pUglyNumbers[pMultiply2Pos] * 2 <= pUglyNumbers[nextUglyIndex])
++pMultiply2Pos;
while (pUglyNumbers[pMultiply3Pos] * 3 <= pUglyNumbers[nextUglyIndex])
++pMultiply3Pos;
while (pUglyNumbers[pMultiply5Pos] * 5 <= pUglyNumbers[nextUglyIndex])
++pMultiply5Pos;
++nextUglyIndex;
}
int ans = pUglyNumbers[nextUglyIndex - 1];
return ans;
}
};
int main()
{
Solution s;
cout << s.GetUglyNumber_Solution(1) << endl;
cout << s.GetUglyNumber_Solution(2) << endl;
cout << s.GetUglyNumber_Solution(3) << endl;
cout << s.GetUglyNumber_Solution(4) << endl;
cout << s.GetUglyNumber_Solution(5) << endl;
system("pause");
return 0;
}