Leetcode-汇总区间C++实现

给定一个  无重复元素 的 有序 整数数组 nums 。

返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。

列表中的每个区间范围 [a,b] 应该按如下格式输出:

"a->b" ,如果 a != b
"a" ,如果 a == b

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> ret;
        int i = 0;
        int n = nums.size();
        while (i < n) {
            int low = i;
            i++;
            while (i < n && nums[i] == nums[i - 1] + 1) {
                i++;
            }
            int high = i - 1;
            string temp = to_string(nums[low]);
            if (low < high) {
                temp.append("->");
                temp.append(to_string(nums[high]));
            }
            ret.push_back(move(temp));
        }
        return ret;
    }
};

思路:记录当前元素并向下逐个对比,当下一个元素值比当前元素值大1时说明区间继续,当该条件不成立时所记录的元素和对比的元素为区间范围,加入结果集。当高低位相等时即大于条件不成立,则之际将值放入结果集中。

没想明白哪儿不对,后边再看吧 

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;
        int count = 0;
        string s;
        for( int i = 0 ; i< nums.size();i++)
        {
            if(count == 0)
            {
                s = to_string(nums[i]);
                count++; 
            }
            else if(nums[i]<nums.size()-1&&nums[i+1]==nums[i]+1)
            {
                count++;
            }
            else if((nums[i]<nums.size()-1&&nums[i+1]!=nums[i]+1)||i == nums.size()-1)
            {
                if(count>1)
                {
                    string temp = s+"->"+to_string(nums[i]);
                    res.push_back(temp);
                    count=0;
                    s="";
                }
                else
                {
                    res.push_back(s);
                    count=0;
                    s="";
                }

            }
        }
        return res;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值