1291 顺次数

题目描述:
我们定义「顺次数」为:每一位上的数字都比前一位上的数字大 1 的整数。
请你返回由 [low, high] 范围内所有顺次数组成的 有序 列表(从小到大排序)。

示例 1:
输出:low = 100, high = 300
输出:[123,234]

示例 2:
输出:low = 1000, high = 13000
输出:[1234,2345,3456,4567,5678,6789,12345]

提示:
10 <= low <= high <= 10^9

方法1:
主要思路:解题链接汇总
(1)确定数字单独最高位的数字,然后模拟生成顺次数的过程,保留符合要求的数字;
(2)由于数字范围内可能有多种位数的数字,故需要最后对数字再进行一次排序;

class Solution {
    
    
public:
    vector<int> sequentialDigits(int low, int high) {
    
    
        vector<int> res;
        for(int i=1;i<10;++i){
    
    //数字的最高位上的数字
            int cur=i;
            int j= i+1;//顺次数的下一个位上的数字
            while(cur<=high){
    
    
                if(cur>=low){
    
    
                    res.push_back(cur);
                }
                if(j>9){
    
    //越界
                    break;
                }
                cur=cur*10+j;
                ++j;//下一个位上的数字
            }
        }
        sort(res.begin(),res.end());//排序
        return res;
    }
};

方法2:
主要思路:
(1)为了省去排序的步骤,这里将各个相同位数的数字存储到一起,最后直接按序取出即可,不需要再单独排序;

class Solution {
    
    
public:
    vector<int> sequentialDigits(int low, int high) {
    
    
        vector<int> res;
        vector<vector<int>> counts(10);
        for(int i=1;i<10;++i){
    
    
            int cur=i;
            int j= i+1;
            int index=1;
            while(cur<=high){
    
    
                if(cur>=low){
    
    
                    counts[index].push_back(cur);//存储到对应的长度数组中
                }
                if(j>9){
    
    
                    break;
                }
                cur=cur*10+j;
                ++j;
                ++index;
            }
        }
        for(vector<int>&vec:counts){
    
    //根据长度,按序取出
            for(int&n:vec){
    
    
                res.push_back(n);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_44171872/article/details/113834725