LeetCode(386)Lexicographical Numbers

来源:互联网 发布:手机照片恢复软件免费 编辑:程序博客网 时间:2024/06/10 21:57

题目

Given an integer n, return 1 - n in lexicographical order.

For example, given 13, return: [1,10,11,12,13,2,3,4,5,6,7,8,9].

Please optimize your algorithm to use less time and space. The input size may be as large as 5,000,000.

分析

给定一个整数,将1~n内的n个整数按照字符串逻辑排序。

代码

/*386. Lexicographical Numbers*/#include <iostream>#include <cstdlib>#include <vector>#include <string>#include <algorithm>using namespace std;class Solution {public:vector<int> lexicalOrder(int n) {vector<int> rs;int i = 1, j;int k;for (;;){// append as many zeroes as possible to the previous numberfor (k = 0; i*pow(10, k) <= n; ++k) rs.push_back(i*pow(10, k));// count continuously until we reach a number that ends with consecutive '9'sfor (j = rs.back() + 1; j <= n && (j % 10) != 0; ++j) rs.push_back(j);// backtraceif (j % 10 == 0){j--;}else{j /= 10;}// find the last non-'9' digitwhile (j % 10 == 9) j /= 10;// start a new sub-sequencei = j + 1;if (rs.size() >= n) break;}return rs;}};int main(){vector<int> res = Solution().lexicalOrder(120);for (auto iter = res.begin(); iter != res.end(); ++iter)cout << *iter << endl;system("pause");return 0;}


0 0
原创粉丝点击