LeetCode 228: 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"].

代码要求对数组中的元素进行分段。


首先给出字符串格式化函数,假设begin==end, 则输出字符串“begin”, 否则输出“begin->end”,代码例如以下:

string format(int begin, int end)
	{
		char buffer[32];
		if (end == begin)
		{
			sprintf(buffer, "%d", begin);
		}else{
			sprintf(buffer, "%d->%d", begin, end);
		}
		return string(buffer);
	}

然后对数组进行分段。代码例如以下:

vector<string> summaryRanges(vector<int>& nums) {
		vector<string> result;
		if (nums.size()<1)
			return result;
		int begin, end;
		begin = end = nums[0];
		for (int i=1; i<nums.size(); i++)
		{
			if (nums[i] ==end || nums[i]==end+1)
			{
				end = nums[i];
			} 
			else
			{
				result.push_back(format(begin, end));
				begin = end = nums[i];
			}
		}
		result.push_back(format(begin, end));
		return result;
	}




原文地址:https://www.cnblogs.com/llguanli/p/6902648.html