Leetcode 264. Ugly Number II

来源:互联网 发布:日本人爱干净 知乎 编辑:程序博客网 时间:2024/06/14 12:58

问题描述

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, and n does not exceed 1690.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

根据题意,要求出第n个ugly数,ugly数表示只有2,3,5质因子的数。那么必然有当前n个数是ugly数,2*pn,3*pn,5*pn也是ugly数,现在的问题就是顺序的问题,必然是这三个数中小的那个排在前面。然后就可以将其转化为三路归并问题。
1,2,3,4,5,6,8,9,10
2*1,2*2,2*3,2*4,2*5…
3*1,3*2,3*3,3*4,3*5…
5*1,5*2,5*3,5*4,5*5…
代码如下:

    public int nthUglyNumber(int n) {        if(n<=0)            return 0;        int[]dp=new int[n];        dp[0]=1;        int index=1;        int i2=0,i3=0,i5=0;        while(index<n){            int temp=Math.min(dp[i2]*2,Math.min(dp[i3]*3,dp[i5]*5));            if(dp[i2]*2==temp)                i2++;            if(dp[i3]*3==temp)                i3++;            if(dp[i5]*5==temp)                i5++;            dp[index++]=temp;        }        return dp[n-1];    }