力扣168,
思路链接:https://www.nowcoder.com/questionTerminal/6aa9e04fc3794f68acf8778237ba065b?answerType=1&f=discussion
答案:
Python
class Solution:
def nthUglyNumber(self, n: int) -> int:
res = [0] * n
res[0] = 1
t2 = t3 = t5 = 0
for i in range(1, n):
res[i] = min(res[t2] * 2, min(res[t3] * 3, res[t5] * 5))
if res[i] == res[t2] * 2:
t2 += 1
if res[i] == res[t3] * 3:
t3 += 1
if res[i] == res[t5] * 5:
t5 += 1
return res[-1]
Java
class Solution {
public int nthUglyNumber(int n) {
int[] array = new int[n];
array[0] = 1;
int t2 = 0, t3 = 0, t5 = 0;
for (int i = 1; i < n; ++i) {
array[i] = Math.min(array[t2] * 2, Math.min(array[t3] * 3, array[t5] * 5));
if (array[i] == array[t2] * 2) {
++t2;
}
if (array[i] == array[t3] * 3) {
++t3;
}
if (array[i] == array[t5] * 5) {
++t5;
}
}
return array[n - 1];
}
}
##Solution1:
最容易想到的,也是最不可能AC的
class Solution {
public:
int GetUglyNumber_Solution(int index) { //输出第index个丑数
int count = 1;
if(index == 1)
return count;
for(int i = 2; ; i++){
if(isUglyNum(i) == true){
count++;
if(count == index)
return i;
}
}
}
bool isUglyNum(int n) {
while (n > 1) {
for (int i = 2; i <= n; i++){
if (n%i == 0){ //如果n能被i整除,i是因子,对i分小于等于5和大于5两种情况讨论
if (i <= 5) {
n /= i;
break;
}
if (i > 5)
return false;
}
}
}
return true;
}
};
##Solution2:
记住这种查数的技巧!!!
答案参考网址:
[1]http://www.cnblogs.com/qqky/p/6964764.html
[2]https://www.nowcoder.com/profile/5810633/codeBookDetail?submissionId=16629921
解题思路:https://blog.youkuaiyun.com/lhanchao/article/details/52079323
本题定义三个变量,对于当前已排好序找到的最大的丑数M,记录恰乘2、乘3、乘5大于当前最大的丑数M的三个位置,然后求三个位置*2 *3 *5的最小值即为下一个丑数的值
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];
}
};
再感慨一句,别人的思路真牛逼啊~