码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(386)Lexicographical Numbers

时间:2016-08-23 22:07:24      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

题目

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 number
			for (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's
			for (j = rs.back() + 1; j <= n && (j % 10) != 0; ++j) rs.push_back(j);

			// backtrace
			if (j % 10 == 0)
			{
				j--;
			}
			else
			{
				j /= 10;
			}

			// find the last non-'9' digit
			while (j % 10 == 9) j /= 10;

			// start a new sub-sequence
			i = 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;
}


LeetCode(386)Lexicographical Numbers

标签:

原文地址:http://blog.csdn.net/fly_yr/article/details/52294920

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!