首页 > 其他 > 详细

【Leetcode】Ugly Number II

时间:2016-05-23 15:16:29      阅读:126      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode.com/problems/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.

思路:
是super ugly number的特殊情况。解法相同。

算法:

    public int nthUglyNumber(int n) {
        int res[]=new int[n];
        int idx[]=new int[3];
        int primes[]=new int[]{2,3,5};
        res[0] = 1;
        for (int i = 1; i < n; i++) {
            int min = Integer.MAX_VALUE;
            for (int j = 0; j < primes.length; j++) {
                min = Math.min(min, primes[j] * res[idx[j]]);
            }
            res[i] = min;
            for (int k = 0; k < primes.length; k++) {
                if (min == res[idx[k]] * primes[k]) {
                    idx[k]++;
                }

            }
        }
        return res[n - 1];

    }

【Leetcode】Ugly Number II

原文:http://blog.csdn.net/yeqiuzs/article/details/51476902

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!