leetcode 228. Summary Ranges

本文介绍了一种使用C++实现的方法来对已排序且不含重复元素的整数数组进行区间总结,通过双端队列存储连续数值并最终返回区间的字符串表示形式。举例说明了如何处理不同的输入情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

228. Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input: [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]

Example 2:

Input: [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]


队列存连续的数值


class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums)
    {
        vector<string> ret;
        if (nums.empty()) return ret;
        deque<int> que;
        
        for (auto it : nums)
        {
            if (que.empty() || que.back() + 1 == it)
            {
                que.push_back(it);
            }
            else
            {
                helper(que, ret);
                que.push_back(it);
            }
        }
        helper(que, ret);
        return ret;
    }
private:
    void helper(deque<int>& que, vector<string>& ret)
    {
        if (que.empty()) return;
        else if (que.size() == 1)
            ret.push_back(to_string(que.back()));
        else
            ret.push_back( to_string(que.front()) + "->" + to_string(que.back()));
        que.clear();
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值