Leetcode—228.汇总区间【简单】

2023每日刷题(五十六)

Leetcode---228.汇总区间

解题思路

我们可以用双指针left 和 right找出每个区间的左右端点。

遍历数组,当right + 1< n 且 nums[right+1]=nums[right]+1 时,指针right向右移动,否则区间 [left, right] 已经找到,将其加入答案,然后将指针left移动到right + 1的位置,继续寻找下一个区间。

实现代码

cpp 复制代码
class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ans;
        auto f = [&](int i, int j) {
            return (i == j) ? to_string(i): to_string(i) + "->" + to_string(j);
        };
        int left = 0, right = 0;
        for(; left < nums.size(); left = right + 1) {
            right = left;
            while(right + 1 < nums.size() && nums[right] + 1 == nums[right + 1]) {
                right++;
            }
            ans.emplace_back(f(nums[left], nums[right]));
        }
        return ans;
    }
};

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
世转神风-6 分钟前
qt-kits-警告:No C++ compiler,无法正常解析工程项目.pro文件
开发语言·c++
王老师青少年编程16 分钟前
csp信奥赛C++标准模板库STL(12):C++ STL 中的 next_permutation详解
c++·stl·排列·标准模板库·csp·信奥赛·permutation
LYFlied18 分钟前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
唯唯qwe-44 分钟前
Day23:动态规划 | 爬楼梯,不同路径,拆分
算法·leetcode·动态规划
做科研的周师兄1 小时前
中国土壤有机质数据集
人工智能·算法·机器学习·分类·数据挖掘
深盾科技1 小时前
融合C++与Python:兼顾开发效率与运行性能
java·c++·python
代码村新手1 小时前
C++-入门
开发语言·c++
来深圳1 小时前
leetcode 739. 每日温度
java·算法·leetcode
神舟之光1 小时前
VSCode编译运行C/C++程序问题及解决方法
开发语言·c++
坐怀不乱杯魂1 小时前
C++ STL unordered_map/set 实现
开发语言·c++