Click here to Skip to main content
15,918,967 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
question link : Loading...[^]

What I have tried:

I am checking if current number is equal to next number+1. if it is not equal simply adding the current number in string : str = to_string(nums[I]) and pushed it in the vector otherwise if nums[I+1] == nums[I]+1 then incrementing I till we get the last number for the range.


vector<string> summaryRanges(vector<int>& nums) {
        vector<string> vec;
        
        int n = nums.size();
        if(n==0) return vec;
        int i =0;
        while(i<n){
            string str ="";
            if(nums[i]+1 != nums[i+1] && i==0){
                str = to_string(nums[i]);
                vec.push_back(str);
            }
           
            else if(nums[i]+1 != nums[i+1] && nums[i-1] != nums[i]-1){
                str = to_string(nums[i]);
                vec.push_back(str);
            }
            else if(nums[i+1] == nums[i]+1){
                int prev = i;
                string s ="";
                while(nums[i+1]==nums[i]+1){
                    i++;
                }  
                    s = to_string(nums[prev])+"->"+to_string(nums[i]);
                    vec.push_back(s);
            }
            i++;
        }
        return vec;
}
Posted
Updated 28-Feb-22 12:44pm
v5
Comments
Patrice T 28-Feb-22 2:14am    
And you plan to tell what is the error message ?

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
C++
#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; // skip the error-producing comparisons
    if ( nums[i] == nums[i+1] )
    {
      // nothing to do
    }
    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;
}
 
Share this answer
 
if(nums[i]+1 != nums[i+1] && i==0)
nums[i+1]:- For your this condition will defiantly thrown the same exception.
Lets have an examplte to understand you the problem. you have an array of 3 numbers like:
int myNum[3] = {10, 20, 30};
and as your you above condition when you are at index:2 [30], according to your condition it will be if(nums[2]+1 != nums[2+1] && i==0) and nums[3] does not exists and throws an exception.
In this scenario you need to run you code numbers index - 1 like while(i< (n - 1)) which will check if(nums[(n-1)]+1 != nums[(n-1)+1] && i==0) and works fine.
 
Share this answer
 
YOU start with i equal zero, and run your loop while i is less than n
Since C++ array and vector indexes start at zero and and at (size - 1), if you try to access any negative index, or an index that is size or greater you will get an "out of range" error.

And your code tries to do both!
        while(i<n){
...
            if(nums[i]+1 != nums[i+1] && i==0){
...
            }
            else if(nums[i]+1 != nums[i+1] && nums[i-1] != nums[i]-1){
...
            }
            else if(nums[i+1] == nums[i]+1){
...
            }
            i++;
        }

I think you need to rethink your whole approach to this loop - we have no idea what it is meant to do, but that isn't the right way to do it!
 
Share this answer
 
CPallini's solution can be written a little more effectively:

C++
// optimized version:
vector<string> summaryRanges(const vector<int>& nums)
{
	vector<string> vec;

	size_t n = nums.size();

	if(n < 1)
		return vec;

	int first = 0;
	int last  = 0;

	for (size_t i = 1; i < n; ++i) {
		if (((nums[i - 1] + 1) != nums[i]) & (nums[i - 1] != nums[i])) {
			vec.push_back(format_range(nums[first], nums[last]));
			first = i;
		}
		last = i;
	}
	vec.push_back(format_range(nums[first], nums[last]));
	return vec;
}

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)
	{
		if(n > 0)
			cout << ",";
		cout << vs[n];  
	}
	cout << "\n";
}
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900