C++ Non-recursive solution


  • 0
    A

    Simple but not the fastest though, since we still try a few invalid incremental numbers.

    25 / 25 test cases passed
    Status: Accepted
    Runtime: 202 ms

    class Solution {
    public:
        vector<int> lexicalOrder(int n) {
            if (n < 1) return vector<int>();
            vector<int> v(n);
            v[0] = 1;
            for (uint i = 1, j = 1, k; i < n; i++) {
                while (1) {
                    if ((k = j * 10) <= n) {
                        v[i] = j = k;
                        break;
                    } else {
                        for (j++; !(j % 10); j /= 10);
                        if (j <= n) {
                            v[i] = j;
                            break;
                        }
                    }
                }
            }
            return v;
        }
    };
    

Log in to reply
 

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