题目
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”].
代码
/*---------------------------------------
* 日期:2015-08-04
* 作者:SJF0115
* 题目: 228.Summary Ranges
* 网址:https://leetcode.com/problems/summary-ranges/
* 结果:AC
* 来源:LeetCode
* 博客:
-----------------------------------------*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
int size = nums.size();
vector<string> result;
if(size == 0){
return result;
}//if
int start = 0;
int end = 0;
for(int i = 1;i <= size;++i){
if(i != size && nums[i] == nums[i-1]+1){
++end;
}//if
else{
if(start == end){
result.push_back(to_string(nums[start]));
}//if
else{
result.push_back(to_string(nums[start])+"->"+to_string(nums[end]));
}//else
start = end + 1;
end = start;
}//else
}//for
return result;
}
};
int main(){
Solution s;
vector<int> vec = {-2,0,1,2,4,5,8,10,14,15,16};
vector<string> result = s.summaryRanges(vec);
for(int i = 0;i < result.size();++i){
cout<<result[i]<<" ";
}//for
cout<<endl;
return 0;
}