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 d2ad4b7

Browse files
committed
"Ugly Number II"
1 parent 7823037 commit d2ad4b7

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
5151
| 267 | [Palindrome Permutation II]| |
5252
| 266 | [Palindrome Permutation]| |
5353
| 265 | [Paint House II]| |
54-
| 264 | [Ugly Number II] | |
54+
| 264 | [Ugly Number II] | [C](src/264.c) |
5555
| 263 | [Ugly Number] | [C](src/263.c) |
5656
| 261 | [Graph Valid Tree]| |
5757
| 260 | [Single Number III] | [C](src/260.c) |

‎src/264.c‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int nthUglyNumber(int n) {
5+
if (n < 2) return 1;
6+
int *nums = (int *)malloc(n * sizeof(int));
7+
nums[0] = 1;
8+
int i2 = 0, i3 = 0, i5 = 0; /* index of 2, 3, 5 respectively */
9+
int k = 1; /* store index */
10+
11+
while (k < n) {
12+
int *index = NULL;
13+
int min = 0;
14+
if (nums[i2] * 2 <= nums[i3] * 3) {
15+
min = nums[i2] * 2;
16+
}
17+
else {
18+
min = nums[i3] * 3;
19+
}
20+
21+
if (nums[i5] * 5 < min) {
22+
min = nums[i5] * 5;
23+
}
24+
25+
nums[k++] = min;
26+
27+
if (nums[i2] * 2 == min) i2++;
28+
if (nums[i3] * 3 == min) i3++;
29+
if (nums[i5] * 5 == min) i5++;
30+
}
31+
32+
int ans = nums[n - 1];
33+
free(nums);
34+
35+
return ans;
36+
}
37+
38+
int main() {
39+
40+
int n = 10;
41+
int i;
42+
for (i = 1; i <= 10; i++) {
43+
printf("%d ", nthUglyNumber(i));
44+
}
45+
printf("\n");
46+
47+
return 0;
48+
}

0 commit comments

Comments
(0)

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