10 line c++ easy understand


  • 39
    L
       vector<string> summaryRanges(vector<int>& nums) {
        const int size_n = nums.size();
        vector<string> res;
        if ( 0 == size_n) return res;
        for (int i = 0; i < size_n;) {
            int start = i, end = i;
            while (end + 1 < size_n && nums[end+1] == nums[end] + 1) end++;
            if (end > start) res.push_back(to_string(nums[start]) + "->" + to_string(nums[end]));
            else res.push_back(to_string(nums[start]));
            i = end+1;
        }
        return res;
    }

  • 3
    R

    similar solution.easier to read.

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

  • 0
    C

    Amazing solution!!


  • 0

    Share my code, similar idea~

    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> result;
            if(!nums.size()) return result;
    	int low = nums[0], high = nums[0];
    	for(int i = 1; i < nums.size(); i++){
    		if (nums[i] == high + 1)
    			high++;
    		else{
    			result.push_back(low == high ? to_string(low) : to_string(low) + "->" + to_string(high));
    			low = high = nums[i];
    		}
    	}
    	result.push_back(low == high ? to_string(low) : to_string(low) + "->" + to_string(high));
    	return result;
        }
    };
    

Log in to reply
 

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