A noted in other solutions, your code is trying to access a 'pass-the-end' item of the input
vector
. You should carefully avoid that.
Introducing two indices, say
first, last
for the
current range, could simplify you task. Try
#include <iostream>
#include <vector>
using namespace std;
string format_range( int a, int b);
vector<string> summaryRanges(const vector<int>& nums);
int main()
{
vector <int> v{0,1,2,4,5,7};
vector <string > vs = summaryRanges(v);
for (size_t n = 0; n < vs.size(); ++n)
{
cout << vs[n];
if ( n == (vs.size()-1)) break;
cout << ",";
}
cout << "\n";
}
string format_range( int a, int b)
{
string s = to_string(a);
if ( b != a)
s += "->" + to_string(b);
return s;
}
vector<string> summaryRanges(const vector<int>& nums)
{
vector<string> vec;
size_t n = nums.size();
int first = -1;
int last;
for (size_t i=0; i < n; ++i)
{
if ( first == -1 )
{
first = i;
last = i;
}
if ( i == (n-1) ) break; if ( nums[i] == nums[i+1] )
{
}
else if ( (nums[i]+1) == nums[i+1])
{
last = i+1;
}
else
{
vec.push_back( format_range( nums[first], nums[last]) );
first = -1;
}
}
if ( first !=-1 )
{
vec.push_back( format_range( nums[first], nums[last]) );
}
return vec;
}