来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ugly-number-ii/solution/chou-shu-ii-by-leetcode/

描述

编写一个程序,找出第n个丑数。丑数就是只包含质因数 2, 3, 5 的正整数。

示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

说明:
1 是丑数。
n 不超过1690。

题解

动态规划

  1. class Ugly {
  2. public int[] nums = new int[1690];
  3. Ugly() {
  4. nums[0] = 1;
  5. int ugly, i2 = 0, i3 = 0, i5 = 0;
  6. for (int i = 1; i < 1690; i++) {
  7. ugly = Math.min(Math.min(nums[i2] * 2, nums[i3] * 3), nums[i5] * 5);
  8. nums[i] = ugly;
  9. if (ugly == nums[i2] * 2) {
  10. i2++;
  11. }
  12. if (ugly == nums[i3] * 3) {
  13. i3++;
  14. }
  15. if (ugly == nums[i5] * 5) {
  16. i5++;
  17. }
  18. }
  19. }
  20. }
  21. class Solution {
  22. public static Ugly u = new Ugly();
  23. public int nthUglyNumber(int n) {
  24. return u.nums[n - 1];
  25. }
  26. }

复杂度分析

  • 时间复杂度:264. 丑数 II(Ugly Number II) - 图1时间检索和大约1690×5=8450次的预计算操作。
  • 空间复杂度:常数空间用保存1690个丑数。