49 丑数
题目
我们把只包含因子2、3和5的数称作丑数(Ugly Number)。求按从小到大的顺序的第1500个丑数。例如6、8都是丑数,但14不是,因为它包含因子7。习惯上我们把1当做第一个丑数。
C++ 题解
空间换时间法:时间效率较高
根据丑数的定义,我们可以知道丑数可以由另外一个丑数乘以2,3或者5得到。因此我们可以创建一个数组,里面的数字是排好序的丑数,每一个丑数都是前面的丑数乘以2,3或者5得到的。
我们把得到的第一个丑数乘以2以后得到的大于M的结果记为M2。同样,我们把已有的每一个丑数乘以3和5,能得到第一个大于M的结果M3和M5。那么M后面的那一个丑数应该是M2,M3和M5当中的最小值:Min(M2,M3,M5)
。比如将丑数数组中的数字按从小到大乘以2,直到得到第一个大于M的数为止,那么应该是2x2=4<M
,3x2=6>M
,所以M2=6
。同理,M3=6
,M5=10
。所以下一个丑数应该是6。
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index < 7)
return index;
vector<int> res(index);
res[0] = 1;
int t2 = 0, t3 = 0, t5 = 0, i;
for (i = 1; i < index; ++i)
{
res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5));
if (res[i] == res[t2] * 2)
t2++;
if (res[i] == res[t3] * 3)
t3++;
if (res[i] == res[t5] * 5)
t5++;
}
return res[index - 1];
}
};
python 题解
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self,index):
if index<=0:
return 0
res=[1]
nextIndex=1
t2=t3=t5=0
while nextIndex<index:
min_val = min(res[t2]*2,res[t3]*3,res[t5]*5)
res.append(min_val)
while res[t2]*2 <= min_val:
t2 += 1
while res[t3]*3 <= min_val:
t3 += 1
while res[t5]*5 <= min_val:
t5 += 1
nextIndex+=1
return res[index-1]