力不从心 Leetcode(ugly number heap) 263, 264,313
Posted wz30
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力不从心 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
以上是关于力不从心 Leetcode(ugly number heap) 263, 264,313的主要内容,如果未能解决你的问题,请参考以下文章