My solution in c++


  • 6
    Z
    class Solution {
    public:
        long nthUglyNumber(int n) {
           set<long> pq;
    		pq.insert(1);
    		int count = 0;
    		long t = 1;
    		while (count < n)
    		{
    			set<long>::iterator it = pq.begin();
    			t = *it;
    			pq.erase(it);
    			pq.insert(t * 2);
    			pq.insert(t * 3);
    			pq.insert(t * 5);
    			count++;
            }
            return t;
        }
    };

  • 1

    Nice idea to use a set. And I now know that long already has 64 bits here, so I can stop using long long :-)

    I just shortened a few things:

    int nthUglyNumber(int n) {
        set<long> pq {1};
        long t;
        while (n--) {
            auto it = pq.begin();
            t = *it;
            pq.erase(it);
            pq.insert(t * 2);
            pq.insert(t * 3);
            pq.insert(t * 5);
        }
        return t;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.