Share my O(n) time, O(1) space solution


  • 1
    O
    class Solution {
    public:
        vector<int> lexicalOrder(int n) {
            vector<int> ans(n);
            int count = 1;
            for (int i = 0; i < n; i++) {
                ans[i] = count;
                if (count * 10 <= n)
                    count *= 10;
                else if (count % 10 == 9) {
                    count++;
                    while (count % 10 == 0)
                        count /= 10;
                }
                else if (count + 1 > n) {
                    count /= 10;
                    count++;
                    while (count % 10 == 0)
                        count /= 10;
                }
                else
                    count++;
            }
            return ans;
        }
    };

  • 0
    Z

    It will be wrong, when n = 192 or something like that.
    It's easy to know that the supposed successor of 192 is 2;
    but in you code, it will be 20.


  • 0
    O

    Thank you for your reminder. I revised my code. Looking forward to hearing more suggestion from you.


Log in to reply
 

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