|
1 | 1 | # [Problem 264: Ugly Number II](https://leetcode.com/problems/ugly-number-ii/description/?envType=daily-question)
|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
| 4 | +- One way to solve this would be: |
| 5 | + - Start the sequence with 1 |
| 6 | + - Each subsequent element is generated by multiplying a previous element by 2, 3, or 5 |
| 7 | + - We could have 3 indices/pointers to keep track of the next thing to multiply by 2/3/5 (initially these should all point to the first element, which is 1). Let's call these `i2`, `i3`, and `i5`. |
| 8 | + - Now we just: |
| 9 | + - Take the current 2/3/5 pointers' numbers and multiply by 2/3/5 |
| 10 | + - Take the minimum of the results (this occurs for pointer `i`). Note: it's possible that *multiple* pointers could match-- e.g., if `i2 == 3` and `i3 == 2` then both the `i2` and `i3` results will be 6. |
| 11 | + - Add it to the list and increment the matching pointer(s) (by 1). |
| 12 | + - Repeat until we've gotten `n` numbers in the sequence and then return the last number in the sequence |
4 | 13 |
|
5 | 14 | ## Refining the problem, round 2 thoughts
|
| 15 | +- Let's see if this works... |
6 | 16 |
|
7 | 17 | ## Attempted solution(s)
|
8 | 18 | ```python
|
9 |
| -class Solution: # paste your code here! |
10 |
| - ... |
| 19 | +class Solution: |
| 20 | + def nthUglyNumber(self, n: int) -> int: |
| 21 | + ugly_numbers = [0] * n |
| 22 | + ugly_numbers[0] = 1 |
| 23 | + |
| 24 | + i2, i3, i5 = 0, 0, 0 |
| 25 | + next2, next3, next5 = 2, 3, 5 |
| 26 | + |
| 27 | + for i in range(1, n): |
| 28 | + x = min(next2, next3, next5) |
| 29 | + ugly_numbers[i] = x |
| 30 | + |
| 31 | + if x == next2: |
| 32 | + i2 += 1 |
| 33 | + next2 = ugly_numbers[i2] * 2 |
| 34 | + |
| 35 | + if x == next3: |
| 36 | + i3 += 1 |
| 37 | + next3 = ugly_numbers[i3] * 3 |
| 38 | + |
| 39 | + if x == next5: |
| 40 | + i5 += 1 |
| 41 | + next5 = ugly_numbers[i5] * 5 |
| 42 | + |
| 43 | + return ugly_numbers[n - 1] |
11 | 44 | ```
|
| 45 | +- Given text cases pass |
| 46 | +- Let's try some others: |
| 47 | + - `n = 1690`: pass |
| 48 | + - `n = 250`: pass |
| 49 | +- Ok, it's probably good; submitting... |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +Woah, apparently this was the way to solve it! |
| 54 | + |
| 55 | + |
0 commit comments