228. Summary Ranges (Medium)

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

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

Solution: Two Pointers

vector<string> summaryRanges(vector<int>& nums) {
    vector<string> res;
    int p1 = 0, p2 = 1, n = nums.size();
    while (p1 < n) {
        while (p2 < n && nums[p2]-nums[p2-1] == 1) ++p2;
        if (p2-p1 == 1) res.push_back(to_string(nums[p1]));
        else res.push_back(to_string(nums[p1])+"->"+to_string(nums[p2-1]));
        p1 = p2; ++p2;
    }

    return res;
}

results matching ""

    No results matching ""