题目:
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
链接:
剑指Offer(第2版):P240
思路标签:
- 算法:空间换时间
解答:
时间效率高,需要辅助空间的解法
- 在求解的过程中,进行从小到大依次求得丑数;
- 每个丑数都是较小的丑数乘以2、3、5得到的;
- 分别用三个指针指向需要分别乘以2、3、5的基丑数;
- 每次取求得的三个丑数中的最小的一个,作为当前要求的丑数。
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index < 0)
return 0;
int *pUglyNumbers = new int[index];
pUglyNumbers[0] = 1;
int nextUglyIndex = 1;
int *pMuliply2 = pUglyNumbers;
int *pMuliply3 = pUglyNumbers;
int *pMuliply5 = pUglyNumbers;
while (nextUglyIndex < index) {
int min = Min(*pMuliply2 * 2, *pMuliply3 * 3, *pMuliply5 * 5);
pUglyNumbers[nextUglyIndex] = min;
while (*pMuliply2 * 2 <= pUglyNumbers[nextUglyIndex])
++pMuliply2;
while (*pMuliply3 * 3 <= pUglyNumbers[nextUglyIndex])
++pMuliply3;
while (*pMuliply5 * 5 <= pUglyNumbers[nextUglyIndex])
++pMuliply5;
++nextUglyIndex;
}
int ugly = pUglyNumbers[index - 1];
delete[] pUglyNumbers;
return ugly;
}
int Min(int number1, int number2, int number3) {
int min = (number1 < number2) ? number1 : number2;
min = (min < number3) ? min : number3;
return min;
}
};