Write a program to find the nth ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and n does not exceed 1690.
C Solution:
#define MIN(a, b) ((a) < (b) ? (a) : (b))
int nthUglyNumber(int n) {
int *dp = malloc(n * sizeof(int));
dp[0] = 1;
int i2 = 0, r2 = dp[i2] * 2;
int i3 = 0, r3 = dp[i3] * 3;
int i5 = 0, r5 = dp[i5] * 5;
int i, last = 1;
for (i = 1; i < n; i++) {
if (r2 <= last) r2 = dp[++i2] * 2;
if (r3 <= last) r3 = dp[++i3] * 3;
if (r5 <= last) r5 = dp[++i5] * 5;
int min = MIN(r2, r3);
last = dp[i] = MIN(min, r5);
}
return dp[n - 1];
}
Summary:
- This is a dynamic programming problem, rather than a heap.
- It is not suit and not good to use heap.
- 6ms, 38.89%
- Be careful about the duplicates.
LeetCode: 264. Ugly Number II





近期评论