​LeetCode刷题实战228:汇总区间

程序IT圈

共 6095字,需浏览 13分钟

 ·

2021-04-06 11:34

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 汇总区间,我们先来看题面:
https://leetcode-cn.com/problems/summary-ranges/

You are given a sorted unique integer array nums.


Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

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

示例


示例 1

输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

示例 2

输入:nums = [0,2,3,4,6,8,9]
输出:["0","2->4","6","8->9"]
解释:区间范围是:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

示例 3

输入:nums = []
输出:[]

示例 4

输入:nums = [-1]
输出:["-1"]

示例 5

输入:nums = [0]
输出:["0"]


解题


思路:直接遍历过去,看到某一个元素和其前面的元素并非相差1的情况下直接将之前的元素打包起来装好就行,在循环遍历结束后再进行一次打包。C++代码如下:


class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> r;
        if(nums.size()==0) return r;
        int a = nums[0];
        int c = nums[0];
        bool b = true;
        for(int i= 1;i<nums.size();i++)
        {
            if(c+1 == nums[i])
            {
                c = nums[i];
            }
            else
            {
                if(b){
                    if(c == a)
                    {
                        r.push_back(to_string(a));
                        b = false;
                        i--;
                    }
                    else
                    {
                        r.push_back(to_string(a)+"->"+to_string(c));
                        b = false;
                        i--;
                    }
                }
                else{
                    a = nums[i];
                    c = nums[i];
                    b = true;
                }
            }
        }
        if(b){
            if(c == a)
            {
                r.push_back(to_string(a));
                b = false;
            }
            else
            {
                r.push_back(to_string(a)+"->"+to_string(c));
            }
        }
        return r;
    }
};



好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-220题汇总,希望对你有点帮助!

LeetCode刷题实战221:最大正方形

LeetCode刷题实战222:完全二叉树的节点个数

LeetCode刷题实战223:矩形面积

LeetCode刷题实战224:基本计算器

LeetCode刷题实战225:用队列实现栈

LeetCode刷题实战226:翻转二叉树

LeetCode刷题实战227:基本计算器 II


浏览 21
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报