题目描述:
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.
这个题先用Ugly Number II的思路去做,超内存了:
public int nthSuperUglyNumber(int n, int[] primes) { List<Deque<Integer>> list =new ArrayList<Deque<Integer>>(); for(int i=0;i<primes.length;i++){ Deque<Integer> queue=new ArrayDeque<Integer>(); queue.offer(1); list.add(queue); } int result=0; for(int i=0;i<n;i++){ int min=Integer.MAX_VALUE; for(int j=0;j<list.size();j++){ min=list.get(j).peek()<min?list.get(j).peek():min; result=min; } for(int j=0;j<list.size();j++){ if(list.get(j).peek()==min){ list.get(j).poll(); } } for(int j=0;j<list.size();j++){ list.get(j).offer(min*primes[j]); } } return result; }
然后想想又用Treeset来解,但是维护一个有序数组空间复杂度太高,超时,WTF:
public int nthSuperUglyNumber(int n, int[] primes) { SortedSet<Integer> set=new TreeSet<Integer>(); int result=0; set.add(1); for(int i=0;i<n;i++){ result=set.first(); set.remove(result); for(int j=0;j<primes.length;j++){ set.add(result*primes[j]); } System.out.println(set); } return result; }最后仔细考虑,上面的方法每次都是取出集合中的第一个数,完全可以将primes.length个list转换成大小为primes.length的数组:
public class Solution { public int nthSuperUglyNumber(int n, int[] primes) { int[] count = new int[primes.length]; int[] res = new int[n]; res[0] = 1; for (int i = 1; i < n; i++) { int min = Integer.MAX_VALUE; for (int j = 0; j < primes.length; j++) { min = Math.min(min, primes[j] * res[count[j]]); } res[i] = min; for (int j = 0; j < count.length; j++) { if (res[count[j]] * primes[j] == min) { count[j]++; } } } return res[n - 1]; } }