Middle-题目81:264. 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.
题目大意:
求第n个丑陋数。
丑陋数指的是质因数只有2,3,5的正整数。注意1是丑数。
题目分析:
其实本题是前面的Middle-题目41的退化情况,相当于求列表[2,3,5]下的超级丑数。因此算法本质与那道题完全一样,只是这次只维护2,3,5三个素数的索引值即可。
源码:(language:java)

public class Solution {
    public int nthUglyNumber(int n) {
        int l1=1,l2=1,l3=1;
        int a,b,c;
        int[] uglyNumber = new int[n+1];
        uglyNumber[1] = 1;
        for(int i = 2;i<=n;i++) {
            a=uglyNumber[l1]*2;
            b=uglyNumber[l2]*3;
            c=uglyNumber[l3]*5;
            int min = min(a,b,c);
            if(min==a)
                l1++;
            if(min==b)
                l2++;
            if(min==c)
                l3++;
            uglyNumber[i]=min;
        }
        return uglyNumber[n];
    }
    private  int min(int a, int b, int c) {
        if(a<=b && a<=c)
            return a;
        else if(b<=a && b<=c)
            return b;
        else 
            return c;
    }
}

成绩:
7ms,beats 96.36%,众数9ms,12.39%

你可能感兴趣的:(Middle-题目81:264. Ugly Number II)