Java TreeSet Solution


  • 0
    Y

    Here is my simple solution by using TreeSet. The reason to use this data structure over PriorityQueue is for handling duplicates. For the time complexity wise it is not the best, but it is relatively clean. Here it is:

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

    Thanks for reading.


Log in to reply
 

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