leetcode 264. 丑数 II python

题目描述:

leetcode 264. 丑数 II python_第1张图片

 题解:

丑数中每个数字都可以由丑数序列u_numbers中之前的数字乘以2 3 5得到

1.用三个idx2 idx3 idx5记录分别用u_numbers中哪个数字乘以2 3 5,idx初始化为0,u_numbers初始化为[1]。

2.分别计算u_numbers[idx2]*2 u_numbers[idx3]*3 u_numbers[idx5]*5,求出三个结果中的最小值next_num,加入u_numbers中,并将对应的idx+1。

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        idx2 = 0
        idx3 = 0
        idx5 = 0
        u_numbers = [1]
        for i in range(n-1):
            number_2 = u_numbers[idx2]*2
            number_3 = u_numbers[idx3]*3
            number_5 = u_numbers[idx5]*5
            next_num = min(number_2,number_3,number_5)
            if next_num==number_2:
                idx2 = idx2+1
            if next_num==number_3:
                idx3 = idx3+1
            if next_num==number_5:
                idx5 = idx5+1
            u_numbers.append(next_num)
        return u_numbers[-1]

leetcode 264. 丑数 II python_第2张图片

 

你可能感兴趣的:(leetcode动态规划,leetcode,python,算法)