LEETCODE 1291. Sequential Digits 解题思路分析

题目大意:

顺次数

我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。

请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。

示例 1:

输出:low = 100, high = 300
输出:[123,234]

示例 2:

输出:low = 1000, high = 13000
输出:[1234,2345,3456,4567,5678,6789,12345]

提示:

  • 10 <= low <= high <= 10^9

如果想查看本题目是哪家公司的面试题,请参考以下免费链接: https://leetcode.jp/problemdetail.php?id=1291

解题思路分析:

自然数中,大于10的顺次数数量并不多(共32个),我们可以列举一下:

12, 23, 34, ... 89 // 2位数共8个,递增11 
123, 234, .... 789 // 3位数共7个,递增111
1234,2345, ...6789 // 4位数共6个
....
123456789          // 9位数共1个

最简单的方法就是按顺序遍历每个顺次数,查看其是否在low和high范围内,如果是就加入返回结果即可。

实现代码:

public List<Integer> sequentialDigits(int low, int high) {
    int length = 2; // 起始顺次数位数为2
    int increase=11; // 起始顺次数递增为11
    int candidate=12; // 首个顺次数为12
    // 返回结果
    List<Integer> res = new ArrayList<>();
    // 当前顺次数小于等于high时
    while(candidate<=high){
        // 当前顺次数
        int num = candidate;
        // 遍历该位数下所有顺次数
        for(int i=0;i<=9-length;i++){
            // 当前顺次数大于high,直接返回
            if(num>high) return res;
            // 当前顺次数在范围内
            if(num>=low&&num<=high){
                res.add(num);
            }
            // 下一个顺次数
            num+=increase;
        }
        // 位数加一
        candidate=candidate*10+ ++length;
        increase = increase*10+1;
    }
    return res;
}

本题解法执行时间为0ms。

Runtime: 0 ms, faster than 100.00% of Java online submissions for Sequential Digits.

Memory Usage: 33.5 MB, less than 100.00% of Java online submissions for Sequential Digits.

本网站文章均为原创内容,并可随意转载,但请标明本文链接
如有任何疑问可在文章底部留言。为了防止恶意评论,本博客现已开启留言审核功能。但是博主会在后台第一时间看到您的留言,并会在第一时间对您的留言进行回复!欢迎交流!
本文链接: https://leetcode.jp/leetcode-1291-sequential-digits-解题思路分析/
此条目发表在leetcode分类目录,贴了, , 标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。