The question description is as such:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
The leetcode gives an example case:
Input: [0] 0 [1] 1 Expected: [1]
I don't understand that. Shouldn't the answer be [0,1]? Since 0 and 1 are all inserted. Could anyone explain that?
Here is my code:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = 0;
int j = 0;
int index = 0;
int []result = new int[nums1.length + nums2.length];
if (nums1 == null || nums2 == null) {
result = null;
}
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) {
result[index++] = nums1[i++];
}
else {
result[index++] = nums2[j++];
}
}
while (i < nums1.length) {
result[index++] = nums1[i++];
}
while (j < nums2.length) {
result[index++] = nums2[j++];
}
}
}
mis the number of elements innums1to be merged, andnfornums2. So it's actually merging[]and[1], but showsnums1as[0]to show it's large enough to store the resultresulttonums1)[0] 0 [1] 1is correct. When it says it has 0 elements, the input is[] 0 [1] 1. problem doesnt mention that the first array contains a number0in it. Hence the output as [1]