码迷,mamicode.com
首页 > 其他好文 > 详细

力不从心 Leetcode(ugly number heap) 263, 264,313

时间:2018-05-03 12:45:44      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:eve   ble   queue   https   next   div   tor   HERE   explain   

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

标签:eve   ble   queue   https   next   div   tor   HERE   explain   

原文地址:https://www.cnblogs.com/stiles/p/LeetcodeUqlynum.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!