Skip to content

Commit 84cef1f

Browse files
committed
🚀 05-Jul-2020
1 parent bd38a2c commit 84cef1f

File tree

2 files changed

+105
-0
lines changed

2 files changed

+105
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
Write a program to find the n-th ugly number.
2+
3+
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
4+
5+
Example:
6+
7+
Input: n = 10
8+
Output: 12
9+
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
10+
Note:
11+
12+
1 is typically treated as an ugly number.
13+
n does not exceed 1690.
14+
Hide Hint #1
15+
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
16+
Hide Hint #2
17+
An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
18+
Hide Hint #3
19+
The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
20+
Hide Hint #4
21+
Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
22+
23+
24+
25+
26+
27+
28+
29+
30+
31+
class Solution {
32+
public:
33+
int nthUglyNumber(int n) {
34+
int ugly[n];
35+
int i2=0, i3=0, i5=0;
36+
int nmt2=2, nmt3=3, nmt5=5; // next multiple
37+
int nun=1; // next ugly number
38+
ugly[0]=1; // first ugly number
39+
for(int i=1;i<n;i++){
40+
nun=min(nmt2, min(nmt3, nmt5));
41+
ugly[i]=nun;
42+
if(nun==nmt2){
43+
i2=i2+1;
44+
nmt2=ugly[i2]*2;
45+
}
46+
if(nun==nmt3){
47+
i3=i3+1;
48+
nmt3=ugly[i3]*3;
49+
}
50+
if(nun==nmt5){
51+
i5=i5+1;
52+
nmt5=ugly[i5]*5;
53+
}
54+
}
55+
return nun;
56+
}
57+
};
58+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
Write a program to find the n-th ugly number.
2+
3+
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
4+
5+
Example:
6+
7+
Input: n = 10
8+
Output: 12
9+
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
10+
Note:
11+
12+
1 is typically treated as an ugly number.
13+
n does not exceed 1690.
14+
15+
16+
17+
18+
19+
20+
21+
class Solution {
22+
public:
23+
int nthUglyNumber(int n) {
24+
int ugly[n];
25+
int i2=0, i3=0, i5=0;
26+
int nmt2=2, nmt3=3, nmt5=5; // next multiple
27+
int nun=1; // next ugly number
28+
ugly[0]=1; // first ugly number
29+
for(int i=1;i<n;i++){
30+
nun=min(nmt2, min(nmt3, nmt5));
31+
ugly[i]=nun;
32+
if(nun==nmt2){
33+
i2=i2+1;
34+
nmt2=ugly[i2]*2;
35+
}
36+
if(nun==nmt3){
37+
i3=i3+1;
38+
nmt3=ugly[i3]*3;
39+
}
40+
if(nun==nmt5){
41+
i5=i5+1;
42+
nmt5=ugly[i5]*5;
43+
}
44+
}
45+
return nun;
46+
}
47+
};

0 commit comments

Comments
 (0)