原题俩接在这里:https://leetcode.com/problems/ugly-number-ii/
题目:
Write a program to find the n
-th 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.
题解:
是Ugly Number的进阶版。找出第n个ugly number.
这里让我们找到第n个丑陋数,还好题目中给了很多提示,基本上相当于告诉我们解法了,根据提示中的信息,我们知道丑陋数序列是从下面3个子列表中选最小值排序的:
(1) 1×2, 2×2, 3×2, 4×2, 5×2, …
(2) 1×3, 2×3, 3×3, 4×3, 5×3, …
(3) 1×5, 2×5, 3×5, 4×5, 5×5, …
仔细观察上述三个列表,我们可以发现每个子列表都是一个丑陋数乘以2,3,5,而这些丑陋数的值就是从已经生成的序列中取出来的,我们每次都从三个列表中取出当前最小的那个加入序列. 就好比把这三条sorted linked list merge起来. dp[i2], dp[i3], dp[i5]都是从[1,2,3,4,5,6,8,9...]里选值, 再比较dp[i2]*2, dp[i3]*3和dp[i5]*5, 选取最小值.
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public int nthUglyNumber(int n) { 3 if(n<1){ 4 return 0; 5 } 6 int [] dp = new int[n]; 7 dp[0] = 1; 8 9 int i2 = 0; 10 int i3 = 0; 11 int i5 = 0; 12 for(int i = 1; i<n; i++){ 13 dp[i] = Math.min(Math.min(dp[i2] * 2, dp[i3] * 3), dp[i5] * 5); 14 if(dp[i] == dp[i2] * 2){ 15 i2++; 16 } 17 if(dp[i] == dp[i3] * 3){ 18 i3++; 19 } 20 if(dp[i] == dp[i5] * 5){ 21 i5++; 22 } 23 } 24 return dp[n-1]; 25 } 26 }