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

264. Ugly Number II

时间:2018-11-06 11:10:04      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:nat   numbers   tor   add   public   ber   while   queue   ati   

Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. 
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.





public int nthUglyNumber(int n) {
    if(n==1) return 1;
    PriorityQueue<Long> q = new PriorityQueue();
    q.add(1l);
    
    for(long i=1; i<n; i++) {
        long tmp = q.poll();
        while(!q.isEmpty() && q.peek()==tmp) tmp = q.poll();
        
        q.add(tmp*2);
        q.add(tmp*3);
        q.add(tmp*5);
    }
    return q.poll().intValue();
}






I think to use TreeSet other than PriorityQueue is easier as you don‘t need to worry about duplicates. Time complexity is same.

public class Solution {
    public int nthUglyNumber(int n) {
        TreeSet<Long> ans = new TreeSet<>();
        ans.add(1L);
        for (int i = 0; i < n - 1; ++i) {
            long first = ans.pollFirst();
            ans.add(first * 2);
            ans.add(first * 3);
            ans.add(first * 5);
        }
        return ans.first().intValue();
    }
}

 

264. Ugly Number II

标签:nat   numbers   tor   add   public   ber   while   queue   ati   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9913094.html

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