C++ concise solution using O(n) time


  • 0
    H
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> ans;
            vector<pair<int, int>> pairs;
            for(int num : nums) {
                if(!pairs.empty() && num == pairs.back().second + 1) pairs.back().second = num;
                else pairs.push_back({num, num});
            }
            for(auto p : pairs) {
                if(p.first != p.second) ans.push_back(to_string(p.first) + "->" + to_string(p.second));
                else ans.push_back(to_string(p.first));
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.