假设我们有一个整数,当且仅当数字中的每个数字都比前一个数字大一个时,它才具有连续数字。我们必须找到[low,high]范围内具有连续数字的所有整数的排序列表。因此,如果低= 100而高= 300,则输出将为[123,234]
为了解决这个问题,我们将遵循以下步骤-
创建一个数组资源
对于我在1到n范围内
x:= 0
对于0到i – 1范围内的k
如果low <x和x <= high,则将x插入ans
x:= 10x +(j + k)
对于j:= 1,直到j + i – 1 <= 9
返回ans
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<int> sequentialDigits(int low, int high) {
vector <int> ans;
for(int i = 1; i <= 9; i++){
for(int j = 1; j + i - 1 <= 9; j++){
int x = 0;
for(int k = 0; k < i; k++){
x = (x*10) + (j + k);
}
if(low <= x && x <= high){
ans.push_back(x);
}
}
}
return ans;
}
};
main(){
Solution ob;
print_vector(ob.sequentialDigits(500, 5000));
}500 5000
输出结果
[567, 678, 789, 1234, 2345, 3456, 4567, ]