C++_Accepted_375ms_73.19%_with brief explanation


  • 0
    • Actually, I just finished this problem according to the test result and find out the logical in the result.

    • Following is the result for n = 233:
      0_1475629850030_75BF681A-F71C-456B-8F76-C7E3C491A3B4.png

    • So we can find out the logical: just put 1, 10, 100, ..., until it is out of n. And the add 1 to the last number, until it is out of n or %10 == 0.

    • Find out the last digit which is not equal to 9, set new i to go back to the while loop. And repeat the algorithm.

    class Solution {
    public:
    vector<int> lexicalOrder(int n) {
        vector<int> res;
        int i = 1;
        while(true){
            while(i <= n){res.push_back(i);i = i*10;}
            int j = res[res.size() - 1] + 1;
            for(; j % 10 != 0 && j <= n; j++){res.push_back(j);}
    
            if(res.size() >= n){break;}
            j = j % 10 == 0 ? j - 1 : j/10;
            while(j % 10 == 9){j = j/10;}
            i = j+1;
        }
        return res;
    }
    };
    

    0_1475630039325_F959F47F-61C7-421D-ACA9-DBAB5323DBD2.png


Log in to reply
 

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