LeetCode(386)Lexicographical Numbers

Posted 逆風的薔薇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(386)Lexicographical Numbers相关的知识,希望对你有一定的参考价值。

题目

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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 386. 字典序排数

(Java) LeetCode 386. Lexicographical Numbers —— 字典序排数

LeetCode 386 字典序排数[dfs 字典树] HERODING的LeetCode之路

LeetCode 386. 字典序排数 / 821. 字符的最短距离 / 388. 文件的最长绝对路径

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

LeetCode.1033-移动石头直到连续(Moving Stones Until Consecutive)