今天和大家聊的问题叫做 汇总区间,我们先来看题面: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; } };
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。