Reputation: 47
I have tried a problem in leetcode IDE. Got a runtime error on running the below code.
As I am a beginner, I'm not able to debug the error.
class Solution
{
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> result;
int n=nums.size();
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=0;j<=i;j++)
{
sum=sum + nums[j];
}
result[i]=sum;
}
return result;
}
};
Upvotes: 1
Views: 2522
Reputation: 1155
The problem in your solution is that result[i]
is not a defined address because result vector is empty, it does not have any size defined.
You can either use result.push_back(sum);
or while declaring vector<int> result(n);
but not both.
Complete code
class Solution
{
public:
vector<int> runningSum(vector<int>& nums) {
int n=nums.size();
vector<int> result(n);
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=0;j<=i;j++)
{
sum=sum + nums[j];
}
result[i]=sum;
}
return result;
}
};
Unrelated but there is an efficient and shorter way to implement this code. Your code has a time complexity of O(n2) but it can be done in O(n) like below:
class Solution
{
public:
vector<int> runningSum(vector<int>& nums) {
int n=nums.size();
vector<int> result(n);
result[0] = nums[0];
for(int i=1;i<n;i++)
{
result[i] = result[i-1] + nums[i];
}
return result;
}
};
Upvotes: 2