228. [LeetCode] Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.





class Solution {
public:
       vector<string> summaryRanges(vector<int>& nums) {
    const int size_n = nums.size();
    vector<string> res;
    if ( 0 == size_n) return res;
    for (int i = 0; i < size_n;) {
        int start = i, end = i;
        while (end + 1 < size_n && nums[end+1] == nums[end] + 1) end++;
        if (end > start) res.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
        else res.push_back(to_string(nums[start]));
        i = end+1;
    }
    return res;
}
};
class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> result;
        if(!nums.size()) return result;
    int low = nums[0], high = nums[0];
    for(int i = 1; i < nums.size(); i++){
        if (nums[i] == high + 1)
            high++;
        else{
            result.push_back(low == high ? to_string(low) : to_string(low) + "->" + to_string(high));
            low = high = nums[i];
        }
    }
    result.push_back(low == high ? to_string(low) : to_string(low) + "->" + to_string(high));
    return result;
    }
};

猜你喜欢

转载自www.cnblogs.com/250101249-sxy/p/10436497.html