Merge Sorted Array
Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/
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 andnums2 are m and n respectively.
算法思想
- nums1的长度是m,nums2的长度是n;从后往前遍历数组,i指向的是nums1的元素,j指向的是nums2的元素
- 如果nums1[i]>nums2[j],就表示该nums1[i]应该往后移动,那么移动多少位呢?应该移动的位数是nums2中还没有被放到nums1中元素的长度,即j+1;
如果nums1[i]<=nums2[j],就将nums2[j]的元素放到i中它该在的位置上,就是i+j+1的位置。
这么做的好处是只需要移动一次数字
3)要注意的是,如果nums1的i移动到-1了,就遍历完了,但是nums2的j>0,也就是说这时候剩下的nums2中的元素就直接放在nums1的前面
程序代码
public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1;
int j = n - 1;
while(j >= 0) {
if (i == -1) {
nums1[j] = nums2[j];
j--;
} else if (nums1[i] > nums2[j]) {
nums1[i + j + 1] = nums1[i];
i--;
} else {
nums1[i +j + 1] = nums2[j];
j--;
}
}
}
}