原题
题目:
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
Reference Answer
思路分析
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
方法一思路:
1、res用来存放排好序的丑数。每一个丑数 n 都是从小于 n 的丑数 乘以 2,3,5 中得来的。
2、所以每次只需要考虑 <= n的丑数中,没有加入res的值,例如为(n-1)*5,那么只需要比较(n-1)*5,(n-1)*2,(n-1)*3的值,取最小存入res.
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index <= 0:
return 0
index_two = index_three = index_five = 0
res = [1]
while len(res) < index:
temp = min(res[index_two] * 2, res[index_three] * 3, res[index_five] * 5)
if not temp in res:
res.append(temp)
if temp % 2 == 0:
index_two += 1
if temp % 3 == 0:
index_three += 1
if temp % 5 == 0:
index_five += 1
return res[index-1]
上述代码可以把判定条件改进地更直观一些:
C++ Version:
class Solution {
public:
int GetUglyNumber_Solution(int index) {
if (index <= 0){
return 0;
}
vector<int> res(index);
int base2 = 0, base3 = 0, base5 = 0;
for(int i = 6; i < index; i++){
res[i] = min(res[base2]*2, min(res[base3]*3, res[base5]*5));
while(res[base2]*2 <= res[i]){
base2 ++;
}
while(res[base3]*3 <= res[i]){
base3++;
}
while(res[base5]*5 <= res[i]){
base5++;
}
}
return res[index-1];
}
};
Python Version:
# -*- coding:utf-8 -*-
class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
if index <= 0:
return 0
res = [1]
base2 = base3 = base5 = 0
for i in range(1, index):
res.append(min(res[base2]*2, res[base3]*3, res[base5]*5))
while res[base2]*2 <= res[i]:
base2 += 1
while res[base3]*3 <= res[i]:
base3 += 1
while res[base5]*5 <= res[i]:
base5 += 1
return res[index-1]
Note:
- 对于 C++ 版本,需要注意的是判定 base2, base3, base5 更新的条件包含等于情况,即:
while(res[base2]*2 <= res[i])
; - 对于 Python 版本,注意首先判定
index <= 0
的情况,因为后面默认 index = 0 时,结果对于为 1;
参考文献:
[1] https://blog.csdn.net/Lynette_bb/article/details/75579740