A easy self explained solution.


  • 0
    Q
    class Solution {
    public:
    	int nthUglyNumber(int n) {
    		queue<int> twoQue, threeQue, fiveQue;
    		int cur = 1;
    		while (--n)
    		{
    			int c;
    			do
    			{
    				twoQue.push(cur * 2);
    				threeQue.push(cur * 3);
    				fiveQue.push(cur * 5);
    				c = min(twoQue.front(), min(fiveQue.front(), threeQue.front()));
    
    				if (c == twoQue.front())
    					twoQue.pop();
    				if (c == threeQue.front())
    					threeQue.pop();
    				if (c == fiveQue.front())
    					fiveQue.pop();
    				if (c != cur)
    				{
    					cur = c;
    					break;
    				}
    			} while (c != cur);
    		}
    		return cur;
    	}
    };

Log in to reply
 

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