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.
Solution:
看 discussion 感觉 test case 有问题?
至少我遇到一个
[1, 2, 4, 5, 6, 0]
5
[3]
1
这样一个case,第一个数组明明有6个元素嘛……
不过我的思路貌似没有受影响
public class Solution
{
public void merge(int[] nums1, int m, int[] nums2, int n)
{
int[] aux = new int[m];
for(int p = 0; p < m; p++)
{
aux[p] = nums1[p];
}
int i = 0, j = 0;
for (int k = 0; k < m + n; k++) //也许是这一行起作用了?
{
if(i >= m)
{
nums1[k] = nums2[j];
j++;
}
else if(j >= n)
{
nums1[k] =aux[i];
i++;
}
else
{
if(aux[i] > nums2[j])
{
nums1[k] = nums2[j];
j++;
}
else
{
nums1[k] = aux[i];
i++;
}
}
}
}
}