-
Notifications
You must be signed in to change notification settings - Fork 0
/
264.ugly-number-ii.go
78 lines (71 loc) · 1.29 KB
/
264.ugly-number-ii.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import "math"
/*
* @lc app=leetcode id=264 lang=golang
*
* [264] Ugly Number II
*
* https://leetcode.com/problems/ugly-number-ii/description/
*
* algorithms
* Medium (42.09%)
* Likes: 2072
* Dislikes: 128
* Total Accepted: 184.2K
* Total Submissions: 436.7K
* Testcase Example: '10'
*
* Write a program to find the n-th ugly number.
*
* Ugly numbers are positive numbers whose prime factors only include 2, 3,
* 5.
*
* Example:
*
*
* 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.
*
* Note:
*
*
* 1 is typically treated as an ugly number.
* n does not exceed 1690.
*
*/
// @lc code=start
func nthUglyNumber(n int) int {
return nthUglyNumber1(n)
}
func nthUglyNumber1(n int) int {
dp := make([]int, n)
dp[0] = 1
twoStep, threeStep, fiveStep := 0, 0, 0
for i := 1; i < n; i++ {
twoVal := dp[twoStep] * 2
threeVal := dp[threeStep] * 3
fiveVal := dp[fiveStep] * 5
dp[i] = min(twoVal, threeVal, fiveVal)
if dp[i] == twoVal {
twoStep++
}
if dp[i] == threeVal {
threeStep++
}
if dp[i] == fiveVal {
fiveStep++
}
}
return dp[n-1]
}
func min(args ...int) int {
min := math.MaxInt32
for _, v := range args {
if v < min {
min = v
}
}
return min
}
// @lc code=end