|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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];
- }
- }
复制代码 |
|