https://leetcode.com/problems/merge-sorted-array/ In this leetcode question, this is the logic, I used
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = 0;
int j = 0;
int k = 0;
vector<int> ans;
while (i<m && j<n) {
if (nums1[i] < nums2[j]){
ans[k ] = nums1[i ];
}
else {
ans[k ] = nums2[j ];
}
}
while (i<m) {
ans[k ] = nums1[i ];
}
while (j<n) {
ans[k ] = nums2[j ];
}
for (int h = 0; h<(m n); h ) {
nums1[h] = ans[h];
}
}
};
while running the code, I get this runtime error. Error Image How do I solve this
CodePudding user response:
This is a vector of size zero
vector<int> ans;
This code attempts to change an element of the size zero vector.
ans[k ] = nums1[i ];
That's the cause of your error.
If you want to add an element to the end of a vector use push_back
ans.push_back(nums1[i ]);
C vectors don't change size automatically, you have to use push_back
or resize
or insert
or something similar.
Alternatively make the vector the correct size to begin with
vector<int> ans(m n);
though I prefer the push_back
method myself.