228.Summary Ranges

2018/10/02 leetcode 共 1047 字,约 3 分钟

title

problem link

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

Example 1:

Input:  [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.
Example 2:

Input:  [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

solution


class Solution {
public:
	vector<string> summaryRanges(vector<int>& nums) {
		vector<string> res;
		if (nums.size() == 0)
			return res;
		int last = nums[0];
		for (int i = 1; i < nums.size(); i++) {
			if (nums[i] - nums[i - 1] == 1) {
				continue;
			}
			else {
				if (nums[i - 1] != last) {
					string s = to_string(last) + "->" + to_string(nums[i - 1]);
					res.push_back(s);
					cout << s << endl;
				}
				else {
					cout << nums[i - 1] << endl;
					res.push_back(to_string(nums[i - 1]));
				}
				last = nums[i];
			}
		}
		if (last != nums[nums.size()-1]) {
			string s = to_string(last) + "->" + to_string(nums[nums.size()-1]);
			res.push_back(s);
		}
		else {
			res.push_back(to_string(nums[nums.size() - 1]));
		}
		return res;
	}
};

Search

    Table of Contents