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.spa
O(M+N) 时间 O(1) 空间code
从后往前填充便可element
先当两个数组都有元素的时候填充大的到末尾,若是有一个数组的数用完了,说明剩下的那个数组的全部数都小于当前填充的位置:it
若是是第一个数组用完了,说明剩下的(最小的那些)全是数组2,把数组2填充进去就行了io
若是是第二个数组用完了,说明剩下的全是数组1,不用填充了,他们已经在了class
public class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m - 1, j = n - 1, writeIdx = m + n - 1; while (i >= 0 && j >= 0) nums1[writeIdx--] = nums1[i] > nums2[j]? nums1[i--] : nums2[j--]; while (j >= 0) nums1[writeIdx--] = nums2[j--]; } }