Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5451945

Browse files
solves ugly numbr ii in java
1 parent 8b64156 commit 5451945

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@
215215
| 260 | [Single Number III](https://leetcode.com/problems/single-number-iii) | [![Java](assets/java.png)](src/SingleNumberIII.java) | |
216216
| 261 | 🔒 [Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree) | | |
217217
| 263 | [Ugly Number](https://leetcode.com/problems/ugly-number) | [![Java](assets/java.png)](src/UglyNumber.java) [![Python](assets/python.png)](python/ugly_number.py) | |
218-
| 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii) | | |
218+
| 264 | [Ugly Number II](https://leetcode.com/problems/ugly-number-ii) | [![Java](assets/java.png)](src/UglyNumberII.java) | |
219219
| 266 | 🔒 [Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation) | | |
220220
| 267 | 🔒 [Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii) | | |
221221
| 268 | [Missing Number](https://leetcode.com/problems/missing-number) | [![Java](assets/java.png)](src/MissingNumber.java) [![Python](assets/python.png)](python/missing_number.py) | |

‎src/UglyNumberII.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// https://leetcode.com/problems/ugly-number-ii
2+
// T: O(N)
3+
// S: O(N)
4+
5+
public class UglyNumberII {
6+
public int nthUglyNumber(int n) {
7+
final int[] dp = new int[n];
8+
dp[0] = 1;
9+
int index2, index3, index5;
10+
index2 = index3 = index5 = 0;
11+
int factor2 = 2, factor3 = 3, factor5 = 5;
12+
13+
for(int i = 1 ; i < n ; i++) {
14+
final int uglyNumber = min(factor2, factor3, factor5);
15+
dp[i] = uglyNumber;
16+
if(factor2 == uglyNumber) factor2 = 2 * dp[++index2];
17+
if(factor3 == uglyNumber) factor3 = 3 * dp[++index3];
18+
if(factor5 == uglyNumber) factor5 = 5 * dp[++index5];
19+
}
20+
21+
return dp[n-1];
22+
}
23+
24+
private int min(int a, int b, int c) {
25+
return Math.min(a, Math.min(b, c));
26+
}
27+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /