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;
}


發佈了360 篇原創文章 · 獲贊 348 · 訪問量 112萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章