編寫一個程序,找出第 n 個丑數。
丑數就是質因數只包含 2, 3, 5 的正整數。
示例:
輸入: n = 10
輸出: 12
解釋: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 個丑數。
說明:
1 是丑數。
n 不超過1690。
解題思路
直接用treeset去重和排序
代碼
class Solution {public int nthUglyNumber(int n) {TreeSet<Long> set=new TreeSet<>();long temp=1;int count=0;set.add(1l);while (count<n){temp=set.pollFirst();count++;set.add(temp*2);set.add(temp*3);set.add(temp*5);}return (int)temp;}
}
動態規劃代碼
class Solution {public int nthUglyNumber(int n) {int[] dp=new int[n+1];int d2=0,d3=0,d5=0;dp[0]=1;for(int i=1;i<n;i++){int min= Math.min(Math.min(dp[d2]*2,dp[d3]*3),dp[d5]*5);//最小的進數組dp[i]=min;if(dp[d2]*2==min) d2++;//已經出現了直接跳到下一個,防止重復if(dp[d3]*3==min) d3++;if(dp[d5]*5==min) d5++;}return dp[n-1];}
}