【问题描述】[中等]
【解答思路】
1. 动态规划
时间复杂度:O(N) 空间复杂度:O(N)
class Solution {public int nthUglyNumber(int n) {int a = 0, b = 0, c = 0;int[] dp = new int[n];dp[0] = 1;for(int i = 1; i < n; i++) {int n2 = dp[a] * 2, n3 = dp[b] * 3, n5 = dp[c] * 5;dp[i] = Math.min(Math.min(n2, n3), n5);if(dp[i] == n2) a++;if(dp[i] == n3) b++;if(dp[i] == n5) c++;}return dp[n - 1];}
}作者:jyd
链接:https://leetcode-cn.com/problems/chou-shu-lcof/solution/mian-shi-ti-49-chou-shu-dong-tai-gui-hua-qing-xi-t/
2. 堆
时间复杂度:O(N) 空间复杂度:O(1)
class Solution {public int nthUglyNumber(int n) {PriorityQueue<Long> pq = new PriorityQueue<>();Set<Long> s = new HashSet<>();//初始化,放进堆和set,发现1要开Long数组才可以long[] primes = new long[]{2, 3, 5};for (long prime : primes) {pq.offer(prime);s.add(prime);}long num = 1;for (int i = 1; i < n; i++) {num = pq.poll();//遍历三个因子for (int j = 0; j < 3; j++) {if (!s.contains(num * primes[j])) {pq.offer(num * primes[j]);s.add(num * primes[j]);}}}return (int) num;}
}作者:jerry_nju
链接:https://leetcode-cn.com/problems/chou-shu-lcof/solution/dui-he-dong-tai-gui-hua-si-lu-xiang-jie-by-jerry_n/
【总结】
1.动态规划流程
第 1 步:设计状态
第 2 步:状态转移方程
第 3 步:考虑初始化
第 4 步:考虑输出
第 5 步:考虑是否可以状态压缩
2.优先队列 按大小弹出 溢出问题long 去重set
参考链接:
https://leetcode-cn.com/problems/chou-shu-lcof/solution/dui-he-dong-tai-gui-hua-si-lu-xiang-jie-by-jerry_n/
参考链接:https://leetcode-cn.com/problems/chou-shu-lcof/solution/mian-shi-ti-49-chou-shu-dong-tai-gui-hua-qing-xi-t/