Sequential Digits (M)
题目
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:
Input: low = 100, high = 300
Output: [123,234]
Example 2:
Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]
Constraints:
10 <= low <= high <= 10^9
题意
在给定范围内找到所有整数,是这些整数满足每一位上的数字都比前一位的数字大1。
思路
所有这样的数字一共才不到一百个,直接遍历所有这样的整数,判断是否在指定范围里。
代码实现
Java
排序
class Solution {
public List<Integer> sequentialDigits(int low, int high) {
List<Integer> list = new ArrayList<>();
int first = 1, num = 1;
while (first <= 8) {
if (num >= low && num <= high) {
list.add(num);
}
if (num > high || num % 10 == 9) {
num = ++first;
continue;
}
num = num * 10 + num % 10 + 1;
}
Collections.sort(list);
return list;
}
}
不排序
class Solution {
public List<Integer> sequentialDigits(int low, int high) {
List<Integer> list = new ArrayList<>();
Queue<Integer> q = new LinkedList<>();
for (int i = 1; i < 9; i++) {
q.offer(i);
}
while (!q.isEmpty()) {
int num = q.poll();
if (num >= low && num <= high) {
list.add(num);
}
if (num <= high && num % 10 < 9) {
q.offer(num * 10 + num % 10 + 1);
}
}
return list;
}
}