问题描述:两个排好序的数组nums1,与nums2。要将这两个数组一起排序存储到nums1中,nums1中有n个元素,nums2中有m个元素。nums1的长度比大于等于m+n。
解决:题目要求使用nums1来存储而不能新建一个空的数组来保存。如果nums1从nums[0]开始从前往后保存新排序的元素,一定会出现新元素将原始元素覆盖的问题。
好在nums1的长度足够,从nums1[n]开始一直到最后都是空的。如果我们将新的元素从后往前填入nums1,便不会出现上述问题。
/*
* Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
* 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.
*/
public class MergeSortedArray {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if(nums1 == null|nums2 == null)
return;
int index1 = m-1;
int index2 = n-1;
int index3 = m+n-1;
while(index1 >=0 && index2 >=0) {
if(nums1[index1] >= nums2[index2]) {
nums1[index3--] = nums1[index1--];
} else {
nums1[index3--] = nums2[index2--];
}
}
while(index2>=0) {
nums1[index3--] = nums2[index2--];
}
}
}
如果出现一方小于 的情况,比如index1小于 ,表示nums1遍历结束,nums2剩余的所有元素均比nums1 小,此时只要把nums2剩余的所有元素放到新数组的
开头即可。当index2小于,表示nums1剩余的所有元素最小,需要放到新数组的开头,但是由于新数组就是使用nums1来保存,所以不再需要额外的赋值操作。
此算法的时间复杂度为omn,空间复杂度为o。