Concise and easy understanding C++ solutions


  • 3
    P
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> ranges;
            if (nums.size() == 0)
                return ranges;
            int lower = 0;
            nums.push_back(INT_MAX);
            for (int i = 1; i < nums.size(); i++) {
                if (nums[i] > nums[i - 1] + 1) {
                    ranges.push_back(num2range(nums[lower], nums[i - 1]));
                    lower = i;
                }
            }
            return ranges;
        }
        
        string num2range(int lower, int upper) {
            if (lower == upper)
                return to_string(lower);
            return to_string(lower) + "->" + to_string(upper);
        }
    };

  • 0
        class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> str_v;
            
            if(nums.size() == 0) return str_v;
            
            string tmp ;
            int32_t range_found = 0;
            
            tmp = to_string(nums[0]);                        
            int32_t prev_elem = nums[0];
            for(auto i=nums.begin()+1; i<nums.end()+1;i++){
                if((i<nums.end()) && (*i == (prev_elem + 1))){
                    range_found = 1;
                }else{//start a new range
                    if(range_found){
                        range_found = 0;
                        tmp += "->";
                        tmp += to_string(prev_elem);
                    }
                    str_v.push_back(tmp);
                    tmp = to_string(*i);                        
                }             
                prev_elem = *i;
            }
            
            return str_v;
        }
    };

  • 0
    9

    pretty concise, but you'd better change

     `nums[i] > nums[i - 1] + 1`  to   nums[i] - 1> nums[i - 1] 
    

    this can help avoid overflow


Log in to reply
 

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