C++ clean solution with explanation (O(N))


  • 1
    D

    Quite standard, just scan the array from the left one by one, and once we find nums[i]!=nums[i-1]+1, then the current range is finished at i-1, so write[start,i-1] to res and update start to i. Be careful about the corner case, which is the last range. In this version, if(i==len) ensures we will put the last range in res.

       class Solution {
        public:
            vector<string> summaryRanges(vector<int>& nums) {
                int len = nums.size(), i, start ;
                vector<string> res;
        
                for(i=1, start=0;i<=len;++i)
                {
                    if(i==len || (nums[i-1] + 1)!=nums[i])
                    { // the current range is finished or it reaches the end of vector, write back
                        res.push_back(((i-1) ==start)? to_string(nums[start]): (to_string(nums[start])+"->"+to_string(nums[i-1])));
                        start = i;
                    }
                }
                return res;
            }
        };

  • 0
    N

    Very clean code. Thank you for sharing.


Log in to reply
 

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