码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Ugly Number II

时间:2016-05-23 15:17:43      阅读:122      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!