题目如下:
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.1 is typically treated as an ugly number. 2.n does not exceed 1690.
264. Ugly Number II
这道题让我们找出第n大的ugly数,ugly数是什么请看[LeetCode每日一题]263. Ugly Number。假设初始时ugly数只有2,3,5,新生成的ugly数都是由原来的ugly数乘2, 乘3, 乘5得来,由此便可以写出代码。
class Solution { public int nthUglyNumber(int n) { if (n <= 0 || n > 1690) return -1; int[] uglys = new int[n]; uglys[0] = 1; int p2 = 0, p3 = 0, p5 = 0; for (int i = 1; i < n; i++) { uglys[i] = Math.min(uglys[p2] * 2, Math.min(uglys[p3] * 3, uglys[p5] * 5)); if (uglys[p2] * 2 == uglys[i]) p2++; if (uglys[p3] * 3 == uglys[i]) p3++; if (uglys[p5] * 5 == uglys[i]) p5++; } return uglys[n - 1]; } }
- 本文固定链接: https://weiguangli.com/archives/476
- 转载请注明: lwg0452 于 Weiguang的博客 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!