LeetcodeUgly Number II

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodeUgly Number II相关的知识,希望对你有一定的参考价值。

题目链接: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];

    

以上是关于LeetcodeUgly Number II的主要内容,如果未能解决你的问题,请参考以下文章

LeetcodeUgly Number II

Single Number II

240. 搜索二维矩阵 II 的三种解法

16 级高代 II 思考题九的七种解法

Permutations II - LeetCode

Single Number II