一、Problem
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.
Input: low = 100, high = 300
Output: [123,234]
Input: low = 1000, high = 13000
Output: [1234,2345,3456,4567,5678,6789,12345]
Constraints:
10 <= low <= high <= 10^9
二、Solution
方法一:構造
從 1 開始,不斷枚舉,構造,比較簡單…
class Solution {
boolean ck(int num) {
String s = num + "";
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i-1) >= s.charAt(i))
return false;
}
return true;
}
public List<Integer> sequentialDigits(int low, int hig) {
String lo = low + "", hi = hig + "";
int min = Integer.parseInt(lo), max = Integer.parseInt(hi);
List<Integer> res = new LinkedList<>();
for (int i = 1; i < 10; i++) {
int num = i, j = i + 1;
while (true) {
num = num * 10 + j;
if (min <= num && num <= max && ck(num)) {
res.add(num);
}
if (num > max)
break;
j++;
}
}
Collections.sort(res);
return res;
}
}
因爲構造出來的數字就是 “有序的”,所以不需要再檢查是否是 順次的…
class Solution {
public List<Integer> sequentialDigits(int low, int hig) {
List<Integer> res = new LinkedList<>();
for (int i = 1; i < 10; i++) {
int num = i;
for (int j = i + 1; j < 10; j++) {
num = num * 10 + j;
if (low <= num && num <= hig)
res.add(num);
if (num > hig)
break;
}
}
Collections.sort(res);
return res;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,