Given two ordered integer arrays nums1 and nums2, please merge nums2 into nums1 to make nums1 an ordered array.
Explanation: Initialize the number of elements of nums1 and nums2 to m and n respectively. You can assume that nums1 has enough space (the size of the space is greater than or equal to m + n) to store the elements in nums2.
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3
Output:
[1,2,2,3,5,6 ]
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
System.arraycopy(nums2, 0, nums1, m, n);
Arrays.sort(nums1);
}
}
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m-1;
int j = n -1;
int len = m+n-1;//从后面sum1空的的往前存储
while(i>=0&&j>=0)
{
if(nums1[i] >=nums2[j])
{
nums1[len--] = nums1[i--];
}else
{
nums1[len--] = nums2[j--];
}
}
//如果先存储完sum2那么sum1剩下的不用比较 本来就在sum1里面了
while(j>=0)//先存储完sum1剩下sum2的继续存储sum1里面
nums1[len--] = nums2[j--];
}