I am doing leetcode problem 88. Here is the link: Merge Sorted Array.
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
I use c++ to solve this problem. But I always got runtime error like this:
Runtime Error Message:
Line 922: Char 34: runtime error: reference binding to null pointer of type 'value_type' (stl_vector.h)
Last executed input:
[1]
1
[]
0
Here is my code:
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int output[m+n] = {0};
int i = 0;
int j = 0;
if(sizeof(nums1) == 0)
{
for(i = 0; i < n; i++)
{
nums1[i] = nums2[i];
}
return;
}
if(sizeof(nums2) == 0)
{
return;
}
for(int k = 0; k < m+n; k++)
{
if(nums1[i] <= nums2[j])
{
if(i < m)
{
output[k] = nums1[i];
i++;
}
else if(j < n)
{
output[k] = nums2[j];
j++;
}
}
else if(nums1[i] >= nums2[j])
{
if(j < n)
{
output[k] = nums2[j];
j++;
}
else if(i < m)
{
output[k] = nums1[i];
i++;
}
}
}
for(i = 0; i < m+n; i++)
{
nums1[i] = output[i];
}
}
};
It's easy to test, just click the link above and copy my code then submit it. I hope someone could help me.
sizeof(nums1) == 0is never true. Neither issizeof(nums2) == 0iandjbefore usingnum1[i]andnum2[j]. UB