Ugly Number II

原题俩接在这里: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.

是维护一个dp数组,每一个ugly number 都是由之前的一个unly number 乘以2,3或者5得到的.

关键在于维护这个从小到大的顺序,可以理解成merge三个linked list. i2, i3, i5记录了分别乘了多少个2, 过少个3, 多少个5. 每次找出dp[i2] *2, dp[i3] *3, dp[i5]*5中最小的一个设为新的dp[i], 同时向后移动对应linked list上的index. list可以理解成前面已经生成的array.

如此可以保证出来的是由小到大的顺序。

Time Complexity: O(n). Space: O(n).

AC Java:

 1 public class Solution {
 2     public int nthUglyNumber(int n) {
 3         if(n<=0){
 4             return 0;
 5         }
 6         int[] dp = new int[n+1];
 7         dp[1] = 1;
 8         int i2 = 1;
 9         int i3 = 1;
10         int i5 = 1;
11         for(int i = 2; i<=n; i++){
12             dp[i] = Math.min(Math.min(dp[i2] * 2, dp[i3] * 3), dp[i5] * 5);
13             if(dp[i] == dp[i2] * 2){
14                 i2++;
15             }
16             if(dp[i] == dp[i3] *3 ){
17                 i3++;
18             }
19             if(dp[i] == dp[i5] *5 ){
20                 i5++;
21             }
22         }
23         return dp[n];
24     }
25 }

你可能感兴趣的:(Ugly Number II)