"Sword Finger Offer" Brush Question Series-(61) Ugly Numbers

topic

We call numbers that only contain prime factors 2, 3, and 5 as Ugly Numbers. Find the nth ugly number in ascending order.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 are the first 10 ugly numbers.

Ideas

Define an array to store n ugly numbers, and then fill the array one by one.

Initialization: The
default 1 is an ugly number, so the first element of the array is 1.

Start to fill in the next number:
each ugly number is obtained by multiplying the ugly number before it by 2, multiplying by 3 or multiplying by 5, but the entire array is sorted when needed, so every time you add a new value, you must ensure It is currently the smallest element that can be added. The minimum value can be obtained by comparison.
Each element in the array will be multiplied by 2, multiplied by 3, and multiplied by 5. Three pointers a, b, c, and a are defined to record the position of the element that has been multiplied by 2, each operation , A points to the next element to be multiplied by 2. The same applies to b and c.

Code

class Solution:
    def nthUglyNumber(self, n: int) -> int:
        dp = [1]*n
        a,b,c = 0,0,0
        for i in range(1,n):
            n1,n2,n3 = dp[a]*2,dp[b]*3,dp[c]*5
            dp[i]=min(n1,n2,n3)
            if n1==dp[i]: a+=1
            if n2==dp[i]: b+=1
            if n3==dp[i]: c+=1
        return dp[-1]

the complexity

Time complexity is O(N)
Space complexity is O(N)

Guess you like

Origin blog.csdn.net/weixin_44776894/article/details/107486268