力不从心 Leetcode(ugly number heap) 263, 264,313
Leetcode ugly number set (3 now)
new ugly number is generated by multiplying a prime with previous generated ugly numbe
Is ugly number or not
class Solution { public boolean isUgly(int num) { if(num==0) return false; //how to generate the number while(num%2==0) num/=2; while(num%3==0) num/=3; while(num%5==0) num/=5; return num==1; } }
//simulate the process to generate the ugly number
--------------------------------------------------------
next level
class Solution { public int nthUglyNumber(int n) { // can store the samle element //use long to safe PriorityQueue<Long> pq = new PriorityQueue<>(); pq.offer(1L); int i = 2; while(i<=n){ long smallest = pq.poll(); while(!pq.isEmpty() && smallest == pq.peek()) pq.poll(); pq.offer(smallest*2); pq.offer(smallest*3); pq.offer(smallest*5); i++; } return pq.poll().intValue(); } }
Key point: use the feature of PriorityQueue: take the min heap.
- PQ could have duplictae number
- Integer is not enough for this problem (negative will affect the PQ)
--------------------------------
next level there are some methods
class Solution { public int nthSuperUglyNumber(int n, int[] primes) { // can store the samle element //use long to safe PriorityQueue<Long> pq = new PriorityQueue<>(); pq.offer(1L); int i = 2; while(i<=n){ long smallest = pq.poll(); while(!pq.isEmpty() && smallest == pq.peek()) pq.poll(); for(int j = 0; j<primes.length; j++){ pq.offer(smallest * primes[j]); } i++; } return pq.poll().intValue(); } }
https://leetcode.com/problems/super-ugly-number/discuss/76291/Java-three-methods-23ms-36-ms-58ms(with-heap)-performance-explained -- mark to learn