leetcode 264. Ugly Number II (Python)

Leetcode 264. Ugly Number II (Python)

Related Topic

Dynamic-Programming.

Description

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

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

Sample I/O

Example 1

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.

Methodology

This question can be solved by Dynamic Programming. However, dp is not the best solution.

let’s start from the array of ugly numbers which contains just one number - 1. Let’s use three pointers i2, i3, i5 to mark the last ugly number which was multiplied by 2, 3 and 5, correspondingly.

The algorithm is straightforward: choose the smallest ugly number among 2*nums[i2], 3*nums[i3], 5*nums[i5] and add it into the array. Move the corresponding pointer by one step. Repeat till you’ll have 1690 ugly numbers.

Code 1

def nthUglyNumber(self, n: int) -> int:
        dp = [1] * (n+1)
        index2, index3, index5 = 1, 1, 1
        for i in range(2, n+1):
            dp[i] = min(2 * dp[index2], 3 * dp[index3], 5 * dp[index5])
            if dp[i] == 2 * dp[index2]: index2 += 1
            if dp[i] == 3 * dp[index3]: index3 += 1
            if dp[i] == 5 * dp[index5]: index5 += 1
        return dp[-1]

BigO

O(1) to retrieve preliminary computed ugly number, and about 1690 x times 5 = 84501690×5=8450 operations for preliminary computations.

Search

    Table of Contents