1291. 顺次数

1291. 顺次数

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

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

示例 1:

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

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

这种量少的题最简单快捷的方法就是打表。

class Solution {
    public List<Integer> sequentialDigits(int low, int high) {
        int[] cur = new int[]{12,23,34,45,56,67,78,89,123,234,345,456,567,678,789,1234,2345,3456,4567,5678,6789,
        12345,23456,34567,45678,56789,123456,234567,345678,456789,1234567,2345678,3456789,12345678,23456789,123456789};
        List<Integer> res = new ArrayList<>();
        for (int i : cur) {
            if (i >= low && i <= high) {
                res.add(i);
            }
        }
        return res;
    }
}

不考虑打表的话可以采用滑动窗口的思路,题目要求的数字显然是“123456789”的一个子数组(连续),那么我们可以从“123456789”中截出大小范围在low和high之间的数。

class Solution {
    public List<Integer> sequentialDigits(int low, int high) {
        List<Integer> res = new ArrayList<>();
        String s = "123456789";
        for(int i = 1; i <= 9; i++) {
            for(int j = 0; j + i <= 9; j++) {
                int num = Integer.parseInt(s.substring(j, j + i));
                if (low <= num && high >= num) {
                    res.add(num);
                }
            }
        }
        return res;
    }
}

可以优化一下窗口长度,但是数据量很小也没必要了。

原文:https://leetcode.cn/problems/sequential-digits/solution/bao-li-mei-ju-by-nice-hermann9a2-uqrc/

posted @ 2022-07-02 15:24  良人呐  阅读(79)  评论(0编辑  收藏  举报