LeetCode -- Ugly Number II

Question:

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.

 

Analysis:

问题描述:写一个程序判断第n个丑数是多少。

思路一:由于前面求过了如何判断一个数是否为丑数,那么可以一次判断每个数是否为丑数,若是丑数,计数器+1,知道计数器==n,时间复杂度较高,Time Limited%>_<%

思路二:又是DP问题。。。还是找不到思路呢。看了网上的解答,由于每个丑数总是有2、3、5相乘构成的。因此用3个list维护已经求出的丑数,然后每次在里面加入当前丑数*2、*3、*5,每次从3个list中取最小的一个作为第i个丑数;

list1 = {1,1*2,2*2,3*2,4*2,5*2,6*2,8*2,……}

list2 = {1,1*3,2*3,3*3,4*3,5*3,6*3,8*3,……}

list3 = {1,1*5,2*5,3*5,4*5,5*5,6*5,8*5,……}

 

Answer:

思路1:

public class Solution {
   public static int nthUglyNumber(int n) {
            int k = 1;
            int res = 1;
        while(true) {
                if(k == n)
                    return res;
                res++;
                if(isUgly(res)) {
                    k++;
                }
        }
    }
    
    
    
    public static boolean isUgly(int num) {
        if(num <= 0)
                return false;
        while(num != 0 && (num%2==0 || num%3==0 || num%5==0)) {
                if(num % 2 == 0)
                    num = num / 2;
                if(num % 3 == 0)
                    num = num / 3;
                if(num % 5 == 0)
                    num = num / 5;
        }
        if(num == 1)
                return true;
        else
                return false;
    }
    
    
}

 

思路2:

public class Solution {
  public static int nthUglyNumber(int n) {
            int res = 0;
            List<Integer> l1 = new ArrayList<Integer>();
            List<Integer> l2 = new ArrayList<Integer>();
            List<Integer> l3 = new ArrayList<Integer>();
            
            l1.add(1);
            l2.add(1);
            l3.add(1);
            
            for(int i=0; i<n; i++) {
                res = Math.min(Math.min(l1.get(0), l2.get(0)), l3.get(0));
                
                if(res == l1.get(0)) l1.remove(0);
                if(res == l2.get(0)) l2.remove(0);
                if(res == l3.get(0)) l3.remove(0);
                
                l1.add(res * 2);
                l2.add(res * 3);
                l3.add(res * 5);
                
            }
            return res;
    }
    
}
posted @ 2015-09-19 20:04  江湖小妞  阅读(237)  评论(0编辑  收藏  举报