Leetcode88_Merge Sorted Array_Easy
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
ExamplInpunums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
思路:
定义三个指针i,j,k,分别指向nums1,nums2,混合数组的末尾。
当nums2有剩余,继续循环,将剩余元素排入混合数组。
nums1有剩余,不用管,因为它本身包含在混合数组里。
注意:
第一个while
while (i >= 0 && j >= 0)
确保nums1/nums2其中一个数组都插进混合数组。不可以
while ( i != 0 && j !=0)
第二个while条件是 j >= 0,也是为了把所有元素插入。
代码:
class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int i = m - 1; j = n - 1; k = m + n - 1; while (i >= 0 && j >= 0){ if (nums1[i] >= nums2[j]) nums1[k--] = nums1[i--]; else nums1[k--] = nums2[j--]; } while (j >= 0) nums1[k--] = nums2[j--]; } }