Leetcode 263-264 ugly number

来源:互联网 发布:犀牛软件安装教程 编辑:程序博客网 时间:2024/05/29 03:35

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.

题意:确定一个数是不是“ugly number”。

题解:简单,直接看代码:

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

这题有意思一点的是其follow up。
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.

即找出第n个ugly number。朴素求解方法是对于每一个数,判断其是不是ugly number,然后数字加一,继续判断,显然效率极差。我们可以从如何构造ugly number 入手。
注意到ugly number为n=(2^i)(3^j)(5^k),所以有以下序列:

1  2x1,2x2,2x3,2x4...2  3x1,3x2,3x3,3x4...3  5x1,5x2,5x3,5x4...

为了维护ugly number的有序性,可以归并以上三个序列,逐次取最小值。详细的分析见代码及注释:

public class Solution {    public int min(int a,int b,int c)//求三个数最小值    {        int Min=a>b? b:a;        return Min>c? c:Min;    }    public int nthUglyNumber(int n) {        int[] s=new int[n];        s[0]=1;//第一个ugly number        int factor2=2,factor3=3,factor5=5;//每个列表的当前比对值        int i,j,k;//三个列表的index        i=j=k=0;//初始化为0        for(int p=1;p<n;p++)        {          int Min_num=min(factor2,factor3,factor5);//取三个列表的当前值重最小那个          s[p]=Min_num;          if(Min_num==factor2)//如果是factor2,则更新factor2的值            factor2=2*s[++i];          if(Min_num==factor3)//同上            factor3=3*s[++j];          if(Min_num==factor5)//同上            factor5=5*s[++k];        }        return s[n-1];    }}
1 0
原创粉丝点击