zoukankan      html  css  js  c++  java
  • 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. For example, [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) 1 is a super ugly number for any given primes.
    (2) The given numbers in primes are in ascending order.
    (3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.

    链接: http://leetcode.com/problemset/algorithms/

    题解:

    超级丑数。跟丑数II很类似,只不过这次primes从2, 3, 5变成了一个size k的list。方法应该有几种,一种是维护一个size K的min-oriented heap,heap里是k个queue,和Ugly Number II的方法一样,取最小的那一个,然后更新其他Queue里的元素,n--,最后n = 1时循环结束。  另外一种是类似dynamic programming的方法,主要参考了larrywant2014大神的代码。维护一个index数组,维护一个dp数组。每次遍历更新的转移方程非常巧妙,min = dp[[index[j]]] * primes[j]。之后再便利一次primes来update每个数在index[]中的使用次数。

    Time Complexity - O(nk), Space Complexity - O(n + k).

    public class Solution {
        public int nthSuperUglyNumber(int n, int[] primes) {
            if(n < 1) {
                return 0;
            }
            int len = primes.length;
            int[] index = new int[len];
            int[] dp = new int[n];
            dp[0] = 1;
            
            for(int i = 1; i < n; i++) {
                int min = Integer.MAX_VALUE;
                for(int j = 0; j < len; j++) {          // try update with all primes
                    min = Math.min(dp[index[j]] * primes[j], min);
                }
                dp[i] = min;                        // find dp[i]
                for(int j = 0; j < len; j++) {      //if prices[j] is used, increase the index
                    if(dp[i] % primes[j] == 0) {
                        index[j]++;
                    }
                }
            }
            return dp[n - 1];
        }
    }

    题外话:

    休假结束,又开始上班啦。不能象前几天一样愉快地刷题了...

    Reference:

    https://leetcode.com/discuss/72878/7-line-consice-o-kn-c-solution

    https://leetcode.com/discuss/72835/108ms-easy-to-understand-java-solution

    https://leetcode.com/discuss/74433/simple-addiction-logic-reduce-the-runtime-28ms-and-beats-77%25

    http://bookshadow.com/weblog/2015/12/03/leetcode-super-ugly-number/

    http://www.cnblogs.com/Liok3187/p/5016076.html

    http://www.hrwhisper.me/leetcode-super-ugly-number/

    http://my.oschina.net/Tsybius2014/blog/547766?p=1

  • 相关阅读:
    linux所有命令失效的解决办法
    第一章 网络基础知识
    RNQOJ 数列
    RNQOJ Jam的计数法
    RNQOJ 开心的金明
    RQNOJ 明明的随机数
    分类讨论的技巧
    Unity 碰撞检测
    Unity --yield return
    Unity 移动方式总结
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5062988.html
Copyright © 2011-2022 走看看