313. Super Ugly Number

Write a program to find the nth super ugly number.

Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.

Example:

Input: n = 12, primes = [2,7,13,19]
Output: 32 
Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19] of size 4.

Note:

1 is a super ugly number for any given primes.
The given numbers in primes are in ascending order.
0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
The nth super ugly number is guaranteed to fit in a 32-bit signed integer.

难度:medium

题目:写程序找出第n个超级丑数。超级丑数是正整数且其公因子由给定的素数组成。

思路:同丑数,三路指针换成一组指针用数组表示。

Runtime: 11 ms, faster than 97.31% of Java online submissions for Super Ugly Number.

Memory Usage: 34.2 MB, less than 82.00% of Java online submissions for Super Ugly Number.

class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        long[] ugly = new long[n];
        ugly[0] = 1;
        int[] p = new int[primes.length];
        
        for (int i = 1; i < n; i++) {
            long minVal = primes[0] * ugly[i - 1];
            for (int j = 0; j < primes.length; j++) {
                long num = ugly[p[j]] * primes[j];
                if (num < minVal) {
                    minVal = num;
                }
            }
            ugly[i] = minVal;
            for (int j = 0; j < primes.length; j++) {
                if (ugly[p[j]] * primes[j] == minVal) {
                    p[j]++;
                }
            }
        }

        return (int) ugly[n - 1];
    }
}

原文 

https://segmentfault.com/a/1190000018384435

本站部分文章源于互联网,本着传播知识、有益学习和研究的目的进行的转载,为网友免费提供。如有著作权人或出版方提出异议,本站将立即删除。如果您对文章转载有任何疑问请告之我们,以便我们及时纠正。

PS:推荐一个微信公众号: askHarries 或者qq群:474807195,里面会分享一些资深架构师录制的视频录像:有Spring,MyBatis,Netty源码分析,高并发、高性能、分布式、微服务架构的原理,JVM性能优化这些成为架构师必备的知识体系。还能领取免费的学习资源,目前受益良多

转载请注明原文出处:Harries Blog™ » 313. Super Ugly Number

赞 (0)
分享到:更多 ()

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址