Very easy-understood C++ code, 0 ms


  • 0
    S
    class Solution {
    public:
        vector<string> summaryRanges(vector<int>& nums) {
            vector<string> result;
            if (nums.size() == 0) return result;
            vector<int> block;
            block.push_back(nums[0]);
            for(int i = 1; i < nums.size(); ++i) {
                if (nums[i] != block.back() + 1) {
                    handleBlock(block, result);
                    block.push_back(nums[i]);
                } else {
                    block.push_back(nums[i]);
                }
            }
            handleBlock(block, result);
            return result;
        }
        
        string getString(int i) {
            char temp[32];
            sprintf(temp, "%d", i);
            return string(temp);
        }
        
        void handleBlock(vector<int>& block, vector<string>& result) {
            if (block.size() > 1) {
                string str = getString(block.front()) + "->" + getString(block.back());
                result.push_back(str);
            } else {
                result.push_back(getString(block.back()));
            }
            block.clear();
        }
    };

  • 0
    A
       vector<string> vec;
    if(nums.size()==0)
    {
    	return vec;
    }
    int gap = 0-nums[0];
    string begin1=int2str(nums[0]);
    string end1;
    for(int i=0;i<=nums.size();i++)
    {
    	if( i!=nums.size()&&i==nums[i]+gap)
    		end1 = int2str(nums[i]);
    	else
    	{
    		if (atoi(end1.c_str())<=atoi(begin1.c_str()))
    		{
    			vec.push_back(begin1);
    		}
    		else
    		{
    			vec.push_back(begin1+"->"+end1);
    		}
    		if (i!=nums.size())
    		{
    			begin1 = int2str(nums[i]);
    			gap = i-nums[i];
    		}
    
    	}
    
    }
    
    return vec;

Log in to reply
 

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