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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/84192.html
標籤:其他
下一篇:信號
