Summary Ranges

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> result;
	    int n = nums.size();
	    if (n < 1)
	    {
		    return result;
	    }

	    int left = 0;
	    int right = 0;
	    char temp[100];
	    for (int i = 1; i < n; i++)
	    {
		    if (nums[i] == nums[right]+1)
		    {
		    	right = i;
		    }
		    else
		    {
			    sprintf(temp, "%d", nums[left]);
			    string str(temp);
			    if (left != right)
			    {
				    sprintf(temp, "%d", nums[right]);
				    str += "->" + string(temp);
			    }
			    result.push_back(str);
			    left = right = i;
		    }
	    }
	    sprintf(temp, "%d", nums[left]);
	    string str(temp);
	    if (left != right)
	    {
		    sprintf(temp, "%d", nums[right]);
		    str += "->" + string(temp);
	    }
	    result.push_back(str);

	    return result; 
    }
};


你可能感兴趣的:(Summary Ranges)