leetcode 263&264: Ugly Number I & II

此题在《剑指offer》中面试题34也有讲解。

Ugly Number I :easy

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

思路:

1.输入时整数,要求是positive number,所以对输入的判断是是否为正数。返回值类型为boolean类型。

2.依次判断是否可以被2,3,5整除。

代码:

public class Solution {
    public boolean isUgly(int num) {
        if(num<=0) return false;
        while(num!=1){
            if(num%2==0) num = num/2;
            else if(num%3==0) num = num/3;
            else if(num%5==0) num = num/5;
            else return false;
        }
        return true;
    }
}


Ugly Number II :medium

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.

Hint:

  1. The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones.
  2. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number.
  3. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3.
  4. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
思路:

1.简单利用ugly number的判断方法,不考虑时间复杂度可以得到解法,算法直观代码简单,但是所有的整数都需要进行计算,时间效率低。

  显示超时,我用eclipse计算了一下输入1352的时间,大概是34秒。

long starTime=System.currentTimeMillis();
long endTime=System.currentTimeMillis();
long Time=endTime-starTime;

代码:

public class Solution {
    public int nthUglyNumber(int n) {
        int count=0;
        int nth=0;
        for(int i=1;count
2.根据丑数的定义,丑数应该另一个丑数乘以2,3,5的结果(除1),这样避免了计算所有的整数。定义三个list,每个list中分别存放2,3,5的倍数,最开始都放入1,然后找到最小的数字,把它的2倍,3倍,5倍分别放到三个表中,依次。要注意的是,把最小的剔除,避免重复的计算。

代码:

public class Solution {  
    public int nthUglyNumber(int n) {  
        int nth = 0;  
        List l1 = new LinkedList();  
        List l2 = new LinkedList();  
        List l3 = new LinkedList();  
        l1.add(1);  
        l2.add(1);  
        l3.add(1);  
          
        for(int i=0; i




你可能感兴趣的:(leetcode)