【发布时间】:2022-01-06 17:33:44
【问题描述】:
我正在尝试解决 leetcode.com Ugly Number II 上的问题。
问题:丑数是一个正整数,其质因数限制为 2、3 和 5。
给定一个整数n,返回第n个丑数。
示例:
输入:n = 10 输出:12 解释:[1, 2, 3, 4, 5, 6, 8, 9, 10, 12] 是前10个丑数的序列。
这是我的解决方案
class Solution {
public int nthUglyNumber(int n) {
int outputNumber = 6;
int temp = 1;
if(n<7){return n;}
int i = 7;
while (i !=(n+1)) {
outputNumber = outputNumber + 1;
temp = outputNumber;
while(temp%5==0){temp=temp/5;}
while(temp%2==0){temp=temp/2;}
while(temp%3==0){temp=temp/3;}
if(temp==1) {
i=i+1;
}
}
return outputNumber;
}
}
这适用于小数字,但是当输入是大数字时,我有 Time Limit Exceeded 问题是如何优化这段代码?
谢谢!
【问题讨论】:
-
请edit发帖并正确格式化代码。
-
除法(和模)运算是最慢的基本数学运算,比加法要长 40-80 倍。所以你可以尝试通过乘法或加法来“构造”那些丑陋的数字。或者,作为像您这样的更直接的方法:将您已经处理的所有数字保存在一个数组中,并在您的 while 循环中检查这些数字是否已经被识别。对于大量数据,这种方式可以节省大量时间,但会消耗 RAM。
-
while(temp%5==0){temp=temp/5;}和temp/(floor(log5(temp))*5)不一样吗? -
@user1984 不是。
标签: java algorithm while-loop