LeetCode 264. 丑数 II

264. 丑数 II

Difficulty: 中等

编写一个程序,找出第 n 个丑数。

丑数就是质因数只包含 2, 3, 5正整数

示例:

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

**说明: **

  1. 1 是丑数。
  2. n 不超过1690。

Solution

本题是263题的延伸题目,把263题的解题思路拿过来,逐个判断每个整数是不是丑数是一种方法,不过效率不高,因为不管是不是丑数都要去验证一遍,比如示例中找出第10个丑数需要验证12次。

因为丑数的质因数只有2/3/5,根据定义,所有的丑数应该是另一个丑数乘以2、3或者5的结果,如果我们提前把丑数计算好并按大小次序放进数组,根据已有的丑数得到后续的丑数就方便多了。

1 是默认已知的丑数U,后面的丑数是前面丑数1乘以2、3或者5的结果,此时的3个结果我们只需要取第一个大于丑数U的结果2作为第二个丑数,至于其他的结果以后再说。

另外需要注意的点是我们没有必要把已有所有的丑数全部都乘以2、3或者5,因为接下来的一个丑数必然是由最接近它(刚好不超过)的丑数乘以2、3或者5得到的,所以每次记住最接近丑数的2/3/5乘数结果位置就可以了。

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        res = [1]
        nextIdx, idx2, idx3, idx5 = 1, 0, 0, 0
        while nextIdx < n:
            uglyNum = min(res[idx2] * 2, res[idx3] * 3, res[idx5] * 5)
            res.append(uglyNum)
            while res[idx2] * 2 <= res[nextIdx]:
                idx2 += 1
            while res[idx3] * 3 <= res[nextIdx]:
                idx3 += 1
            while res[idx5] * 5 <= res[nextIdx]:
                idx5 += 1
            nextIdx += 1
        return res[nextIdx-1]

相关题目:

  1. LeetCode 263. 丑数 - swordspoet - 博客园
posted @ 2021-04-10 16:08  swordspoet  阅读(59)  评论(0编辑  收藏  举报