Skip to content

Latest commit

 

History

History
61 lines (45 loc) · 1.78 KB

228-summary-ranges.md

File metadata and controls

61 lines (45 loc) · 1.78 KB

228. Summary Ranges - 汇总区间

给定一个无重复元素的有序整数数组,返回数组区间范围的汇总。

示例 1:

输入: [0,1,2,4,5,7]
输出: ["0->2","4->5","7"]
解释: 0,1,2 可组成一个连续的区间; 4,5 可组成一个连续的区间。

示例 2:

输入: [0,2,3,4,6,8,9]
输出: ["0","2->4","6","8->9"]
解释: 2,3,4 可组成一个连续的区间; 8,9 可组成一个连续的区间。

题目标签:Array

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 0 ms 872.4 KB
class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;
        if (nums.empty()) return res;
        int i = 0;
        while (i < nums.size()) {
            int st = nums[i];
            int ed = st;
            while (i < nums.size() - 1 && nums[i+1] - nums[i] == 1) {
                ed = nums[i+1];
                i++;
            }
            if (st == ed) {
                res.push_back(to_string(st));
            } else {
                string s = to_string(st) + "->" + to_string(ed);
                res.push_back(s);
            }
            i++;
        }
        return res;
    }
};
static auto _ = [](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();