313. Super Ugly Number

栏目: Java · 发布时间: 7年前

内容简介: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:

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];
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Intersectional Internet

The Intersectional Internet

Safiya Umoja Noble、Brendesha M. Tynes / Peter Lang Publishing / 2016

From race, sex, class, and culture, the multidisciplinary field of Internet studies needs theoretical and methodological approaches that allow us to question the organization of social relations that ......一起来看看 《The Intersectional Internet》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具