leetcode: 264. Ugly Number II

题目

Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.

Note:  

  1. 1 is typically treated as an ugly number.
  2. n does not exceed 1690.

 

思路

这题的思路很有意思。

1、对于 乘积因子 2,3,5 记录他们该乘列表中的哪个数了。

2、三个因子 乘各自该乘的数,然后选择其中最小的,附在列表后面。

3、更新 因子该乘的数 (由于数字是从小到大排列的,所以因子该乘的数,为列表中该因子当前所乘数的下一个),用图来表示:

 

答案

    def nthUglyNumber(self, n: int) -> int:
        i2,i3,i5 = 0,0,0
        uglyNums = [1]
        n0 = 1
        while n0 < n:
            u2, u3, u5 = 2*uglyNums[i_f2], 3*uglyNums[i_f3], 5*uglyNums[i_f5]
            u_min = min([u2, u3, u5])
            
            # 这里可能出现成绩结果相同的情况,所以需要对每个factor更新,而不是只更新乘积的
            if u_min == u_multiply2:
                i_f2 += 1
            if u_min == u_multiply3:
                i_f3 += 1
            if u_min == u_multiply5:
                i_f5 += 1
            uglyNums.append(u_min)
            n0+=1
        return uglyNums[-1]
发布了45 篇原创文章 · 获赞 1 · 访问量 3376

猜你喜欢

转载自blog.csdn.net/qq_22498427/article/details/104470314