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--]; } }