题目

An integer has sequential digits if and only if each digit in the number is one more than the previous digit.

Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.

Example 1:

  1. Input: low = 100, high = 300
  2. Output: [123,234]

Example 2:

  1. Input: low = 1000, high = 13000
  2. Output: [1234,2345,3456,4567,5678,6789,12345]

Constraints:

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

题意

在给定范围内找到所有整数,是这些整数满足每一位上的数字都比前一位的数字大1。

思路

所有这样的数字一共才不到一百个,直接遍历所有这样的整数,判断是否在指定范围里。


代码实现

Java

排序

  1. class Solution {
  2. public List<Integer> sequentialDigits(int low, int high) {
  3. List<Integer> list = new ArrayList<>();
  4. int first = 1, num = 1;
  5. while (first <= 8) {
  6. if (num >= low && num <= high) {
  7. list.add(num);
  8. }
  9. if (num > high || num % 10 == 9) {
  10. num = ++first;
  11. continue;
  12. }
  13. num = num * 10 + num % 10 + 1;
  14. }
  15. Collections.sort(list);
  16. return list;
  17. }
  18. }

不排序

  1. class Solution {
  2. public List<Integer> sequentialDigits(int low, int high) {
  3. List<Integer> list = new ArrayList<>();
  4. Queue<Integer> q = new LinkedList<>();
  5. for (int i = 1; i < 9; i++) {
  6. q.offer(i);
  7. }
  8. while (!q.isEmpty()) {
  9. int num = q.poll();
  10. if (num >= low && num <= high) {
  11. list.add(num);
  12. }
  13. if (num <= high && num % 10 < 9) {
  14. q.offer(num * 10 + num % 10 + 1);
  15. }
  16. }
  17. return list;
  18. }
  19. }