My C++ 0ms solution, easy to understand


  • 0
    S
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> res; 
            stringstream sstm;
            if(nums.size()==0){
                return res;
            }
            
            int start;
            start = nums[0];
            int index = 0;
            for(int i=0;i<nums.size();i++){
                if(nums[i]!=start+i-index){
                    if(nums[i-1] == start){
                        sstm<<start;
                        res.push_back(sstm.str());
                        sstm.str("");
                        start = nums[i];
                        index = i;
                    }
                    else if(nums[i-1]> start){
                        sstm<<start;
                        sstm<<"->";
                        sstm<<nums[i-1];
                        res.push_back(sstm.str());
                        sstm.str("");
                        start = nums[i];
                        index =i;
                    }
                }
                if(i == nums.size()-1){
                    if(nums[i]==start){
                        sstm<<start;
                        res.push_back(sstm.str());
                        sstm.str("");
                        start = nums[i];
                        index = i;
                    }else{
                        sstm<<start;
                        sstm<<"->";
                        sstm<<nums[i];
                        res.push_back(sstm.str());
                        sstm.str("");
                        start = nums[i];
                        index =i;
                    }
                }
            }
            
            return res;
            
        }
    };

Log in to reply
 

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