鱼C论坛

 找回密码
 立即注册
查看: 1837|回复: 0

[学习笔记] leetcode 313. Super Ugly Number

[复制链接]
发表于 2019-9-24 09:49:32 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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.
class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] arr = new int [n+1];
        arr[1] = 1;
        HashMap <Integer, Integer> map = new HashMap<>();
        
        for(int i = 0; i< primes.length ; i++){
            map.put(primes[i], 1);
        }
        for(int i = 2; i <= n ; i++){
            
            int min = Integer.MAX_VALUE;
            
            for(Integer key : map.keySet()){
                
                if(key * arr[map.get(key)] < min){
                    min = key * arr[map.get(key)];
                }
                
            }
            for(Integer key : map.keySet()){
                
                if(key * arr[map.get(key)] == min){
                    map.put(key, map.get(key)+1);
                }
                
            }
            arr[i] = min;
        }
        return arr[n];
    }
}
class Solution {
    public int nthSuperUglyNumber(int n, int[] primes) {
        int[] val = new int[primes.length];
        int[] idx = new int[primes.length];
        int[] ugly = new int[n+1];
        Arrays.fill(val,1);
        int next = 1;
        for(int i = 0; i < n ; i++){
            ugly[i] = next;
            next = Integer.MAX_VALUE;
            for(int j = 0; j< primes.length;j++){
                if(ugly[i] == val[j]) val[j] = primes[j] * ugly[idx[j]++];
                next = Math.min(val[j], next);
            }
        }
        
        return ugly[n-1];
    }
}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-24 21:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表