LeetCode - 228. Summary Ranges - 思路详解- C++

48 篇文章 0 订阅
43 篇文章 0 订阅

题目

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

For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].

翻译

假设有一个已排序整数数组,不包含重复的元素,返回其范围摘要

思路

开始定义一个范围的起始地址。
遍历数组,如果连续,则继续遍历,如果不连续,则出现一段,得到范围结束地址,保存结果即可。
更新起始地址,接着遍历

代码

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;
        int start = 0;    //最小值
        int end = nums.size(); //最大值
        if(end == 0){
            return res;
        }
        int t_s = nums[0];  //初始值
        int t_e = nums[0];  //终点值
        int i = start;
        while(i < end){
            if(i+1 < end && nums[i] + 1 == nums[i+1]){

            }else{
                //如果不相等,出现断
                t_e = nums[i];
                string s;
                if(t_e == t_s){
                    s+= to_string(t_s);
                }else{
                    s+= to_string(t_s);
                    s+= "->";
                    s+= to_string(t_e);   
                }

                res.push_back(s);

                //更新新的起始地址
                t_s = nums[i+1];
            }
            i++;
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值