Neat and easy understand Java Solution, 6ms


  • 1
    Y
        public int nthUglyNumber(int n) {
            int[] ugly = new int[n+1];
            ugly[1] = 1;
            int num2 = 2, num3 = 3, num5 = 5;
            int index2 = 1, index3 = 1, index5 = 1;
            for(int i = 2; i <= n; ++i) {
                ugly[i] = Math.min(num2, Math.min(num3, num5));
                if (num2 == ugly[i]) num2 = ugly[++index2] * 2;
                if (num3 == ugly[i]) num3 = ugly[++index3] * 3;
                if (num5 == ugly[i]) num5 = ugly[++index5] * 5;
            }
            return ugly[n];
        }
    

Log in to reply
 

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