[LeetCode] Lexicographical Numbers 字典序排列数字

声明:原题目转载自LeetCode,解答部分为原创

Problem :

       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.

Solution :

         思路:按序输出以 1 为首位、2 为首位 、 3 为首位的各位数。本题的关键是四种数值转换方式,第一种是 原数值 + 1, 第二中 是 1 -> 10 ->  100 -> 1000 -> 10000 <= n, 第三种是 1099 -> 11, 第四种是 (n = 23为例)23 -> 3

        代码如下:


#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    vector<int> lexicalOrder(int n) {
        vector<int> out;
        
        int number = 1;
        for(int i = 1; i <= n ; i ++)
        {
        	out.push_back(number);
        	// case_1 :: 1 -> 10 -> 100 -> 1000
        	if(number * 10 <= n)
        	{
        		number *= 10;
        		continue;
			}
			//case_2 :: add 100--01, 100-02, 100-03, --- , 100-08, 100-09
			if(number % 10 < 9 && number + 1 <= n)
			{
				number ++;
				continue;
			}
			else
			//case_3 :: take ex n = 23 : 23 -> 3 ; n = 1400 : 1099 -> 11
			{
				while( (number / 10 ) % 10 == 9 )
				    number /= 10;
				number = number / 10 + 1;
			}
		}
		return out;
    }
};

int main()
{
	Solution text;
	vector<int> output = text.lexicalOrder(13);
	for(int i = 0 ; i < output.size() ; i ++)
	{
		cout << output[i] << " ";
	}
	cout << endl;
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值