My c++ solution, 16 ms.


  • 1
    H
    class Solution {
        public:
            int nthUglyNumber(int n) {
                if (n == 1)
                    return 1;
                vector<int> v2(n, 0), v3(n, 0), v5(n, 0);
                v2[0] = 2;
                v3[0] = 3;
                v5[0] = 5;
                int a = 0, b = 0, c = 0;
                int count = 1, ret = 0, i = 1;
                while (count != n) {
                    ret = min(v2[a], min(v3[b], v5[c]));
                    v2[i] = 2 * ret;
                    v3[i] = 3 * ret;
                    v5[i] = 5 * ret;
                    if (v2[a] == ret)
                        ++ a;
                    if (v3[b] == ret)
                        ++ b;
                    if (v5[c] == ret)
                        ++ c;
                    ++ i;
                    ++ count;
                }
                return ret;
            }
        };

Log in to reply
 

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