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"].
[Thoughts]
一道实现题,本身并没有难度,处理好相关的merge即可。
[Code]
1: vector<string> summaryRanges(vector<int>& nums) {
2: vector<string> result;
3: if(nums.size() <1) return result;
4:
5: int start = 0, i =1;
6: for(; i< nums.size(); i++){
7: if(nums[i] - nums[i-1]==1) continue;
8:
9: if(i-1 == start) {
10: result.push_back(to_string(nums[start]));
11: } else
12: result.push_back(to_string(nums[start]) + "->" + to_string(nums[i-1]));
13: start = i;
14: }
15:
16: if(i-1 == start) {
17: result.push_back(to_string(nums[start]));
18: } else
19: result.push_back(to_string(nums[start]) + "->" + to_string(nums[i-1]));
20: return result;
21: }
No comments:
Post a Comment