[Leetcode] 力扣228:汇总区间
作者:互联网
思路
尽可能的一次遍历处理问题,本质上还是双指针的问题,始终用一个变量维护边界的最左值,遍历寻找最右值,判断左右相等还是不相等插入对应值
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res;
int n = nums.size();
int left = 0;
for (int i = 0; i < n; ++i) {
if (i + 1 == n || nums[i] + 1 != nums[i + 1]) {
if (i == left) res.emplace_back(to_string(nums[left]));
else res.emplace_back(to_string(nums[left]) + "->" + to_string(nums[i]));
left = i + 1;
}
}
return res;
}
};
标签:string,nums,int,res,力扣,vector,228,Leetcode,left 来源: https://blog.csdn.net/weixin_44537258/article/details/112426133