leetcode 386. Lexicographical Numbers

257 篇文章 17 订阅

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开头的数字、以2开头的数字、.......以9开头的数字分开来。然后以1开头的数字为例,我们在其后的每个数字后加上0~9。就像下图的树一样。


public List<Integer> lexicalOrder(int n) {
	List<Integer> list=new ArrayList<Integer>();
	for(int i=1;i<=9;i++){
		helper(i, n, list);
	}		
	return list;
}

public void helper(int number,int n,List<Integer> list){
	if(number>n){
		return;
	}
	else{
		list.add(number);
		for(int i=0;i<=9;i++){
			helper(10*number+i, n, list);
		}
	}
	return;
}
大神则用了时间复杂度为O(n) , 空间复杂度为O(1) 的迭代方法。
public List<Integer> lexicalOrder(int n) {
        List<Integer> list = new ArrayList<>(n);
        int curr = 1;
        for (int i = 1; i <= n; i++) {
            list.add(curr);
            if (curr * 10 <= n) {
                curr *= 10;
            } else if (curr % 10 != 9 && curr + 1 <= n) {
                curr++;
            } else {
                while ((curr / 10) % 10 == 9) {
                    curr /= 10;
                }
                curr = curr / 10 + 1;
            }
        }
        return list;
}
思路是找到:往 list 中加的后一个元素。
以当前数字为45来举个例子: 如果当前数字是45,那么下一个数字将是450 (450 == 45 * 10)(if 450 <= n), 或者 46 (46 == 45 + 1) (if 450>n and 46 <= n) 或者 5 (5 == 45 / 10 + 1) (因为5<45,所以肯定5<n).
又以 n = 600 来举个例子, 如果当前数字是 499, 那么下一个数字是5,因为在499中 "4" 后面全是 “9”,所以要一直用10来除499,直到下一个数字不是9。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值