Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and n does not exceed 1690.
一刷
題解:
用三個(gè)隊(duì)列巾钉,保存2翘狱,3,4乘上ugly number后的值砰苍,注意潦匈,為了避免重復(fù),2的隊(duì)列不乘3赚导,5隊(duì)列中的值茬缩,3中不乘5隊(duì)列中的值。
public class Solution {
public int nthUglyNumber(int n) {
if(n<1) return 0;
Queue<Long> q2 = new LinkedList<>();
Queue<Long> q3 = new LinkedList<>();
Queue<Long> q5 = new LinkedList<>();
q2.add(2L);
q3.add(3L);
q5.add(5L);
Long res = 1L;
while(n>1){
if(q2.peek() < q3.peek() && q2.peek() < q5.peek()){
res = q2.poll();
q2.add(res*2);
q3.add(res*3);
q5.add(res*5);
}
else if(q3.peek() < q2.peek() && q3.peek() < q5.peek()){
res = q3.poll();
q3.add(res*3);
q5.add(res*5);
} else{
res = q5.poll();
q5.add(res*5);
}
}
return res.intValue();
}
}
但是這樣會(huì)出現(xiàn)超時(shí)吼旧,改用array, 并用3個(gè)index記錄下一個(gè)*2/3/5的值
public class Solution {
public int nthUglyNumber(int n) {
if (n <= 0) return 0;
int[] dp = new int[n];
dp[0] = 1;
int index2 = 0, index3 = 0, index5 = 0;
for (int i = 1; i < n; i++) {
dp[i] = Math.min(2 * dp[index2], Math.min(3 * dp[index3], 5 * dp[index5]));
if (dp[i] == 2 * dp[index2]) index2++;
if (dp[i] == 3 * dp[index3]) index3++;
if (dp[i] == 5 * dp[index5]) index5++;
}
return dp[n - 1];
}
}
二刷
同上
public class Solution {
public int nthUglyNumber(int n) {
if(n<=0) return 0;
int[] dp = new int[n];
dp[0] = 1;
int index2 = 0, index3 = 0, index5=0;
for(int i=1; i<n; i++){
dp[i] = Math.min(Math.min(2*dp[index2], 3*dp[index3]), 5*dp[index5]);
if (dp[i] == 2 * dp[index2]) index2++;
if (dp[i] == 3 * dp[index3]) index3++;
if (dp[i] == 5 * dp[index5]) index5++;
}
return dp[n-1];
}
}
index2與index3凰锡,index5可以通過(guò)同一個(gè)數(shù)一起增加,比如index2 = 3, index3 = 2, 當(dāng)前最小的數(shù)為6,那么index2++寡夹, index3++