386. Lexicographical Numbers 把1--n按字典序排序

https://leetcode.com/problems/lexicographical-numbers/description/

 

前20个是

1, 10, 11, 12, 13, 14, .....19 2, 20, 3, 4, 5, 6, ....9

class Solution {
public:
    vector<int> lexicalOrder(int n) {
        vector<int> ans;
        int cur = 1;
        for (int i = 1; i <= n; ++i) {
            ans.push_back(cur);
            if (cur * 10 <= n) {
                cur *= 10;
            } else if (cur % 10 != 9 && cur + 1 <= n) {
                cur++;
            } else {
                cur += 10;
                cur -= cur % 10;
                while (cur % 10 == 0) cur /= 10;
            }
        }
        return ans;
    }
};

 

posted on 2018-08-19 20:47  stupid_one  阅读(360)  评论(0编辑  收藏  举报

导航