一、题目
给你两个按 非递减顺序 排列的整数数组 nums1
和 nums2
,另有两个整数 m
和 n
,分别表示 nums1
和 nums2
中的元素数目。
请你 合并 nums2
到 nums1
中,使合并后的数组同样按 非递减顺序 排列。
注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1
中。为了应对这种情况,nums1
的初始长度为 m + n
,其中前 m
个元素表示应合并的元素,后 n
个元素为 0
,应忽略。nums2
的长度为 n
。
二、第一思路:双指针+辅助数组
-
思路
创建辅助数组,从前向后,依次从nums1和nums2数组中选择最小的,大小相同优先放nums1的。题目中规定说,最后的结果保存在nums1中,因此需要重新将辅助数组中的内容搬到nums1中。
-
代码
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int auxiliaryArray[] = new int[m+n];//辅助数组
//nums1、nums2、auxiliaryArray的左指针
int l1 = 0;
int l2 = 0;
int l3 = 0;
while (l3<m+n){
//nums1结束
if (l1 == m){
auxiliaryArray[l3] = nums2[l2];
l2++;
l3++;
continue;
}
//nums2结束
if (l2 == n){
auxiliaryArray[l3] = nums1[l1];
l1++;
l3++;
continue;
}
//还没结束,双指针选最小的放到辅助数组
if (nums1[l1]<=nums2[l2]){
auxiliaryArray[l3] = nums1[l1];
l1++;
l3++;
}else {
auxiliaryArray[l3] = nums2[l2];
l2++;
l3++;
}
}
//将辅助数组中的内容放到nums1中
for (int i = 0; i < auxiliaryArray.length; i++) {
nums1[i] = auxiliaryArray[i];
}
}
-
分析
时间复杂度:O(m+n)。
空间复杂度:O(m+n),创建辅助数组的原因。
-
结果
三、第二思路:逆向双指针
-
思路
nums1本身的长度已经足够存储所有元素,但是第一种方法没有去利用nums1空闲的空间,而是重新创建辅助数组,其实是对空间的一个浪费。
nums1空闲的位置处于数组的右侧,这部分在结果中应该存放合并后较大的数字。
不妨我们先将大的数字拿出来,按序放在nums1的右侧,从右向左依次选择剩下数字中最大的。
-
代码
/**
*
* @param nums1
* @param m
* @param nums2
* @param n
*/
public static void invertedDoublePointer(int[] nums1, int m, int[] nums2, int n) {
//三个右指针,从右侧逐渐减小;
int l1 = m-1;
int l2 = n-1;
int l3 = m+n-1;
while (l3>=0){
//nums1结束
if (l1 < 0){
nums1[l3] = nums2[l2];
l2--;
l3--;
continue;
}
//nums2结束
if (l2 < 0){
nums1[l3] = nums1[l1];
l1--;
l3--;
continue;
}
//nums1更大
if (nums1[l1]>nums2[l2]){
nums1[l3] = nums1[l1];
l1--;
l3--;
continue;
}
//nums2更大
if (nums1[l1]<=nums2[l2]){
nums1[l3] = nums2[l2];
l2--;
l3--;
}
}
}
-
分析
时间复杂度:O(m+n)。
空间复杂度:O(1),原地移动元素,无需额外空间。
-
结果
四、第二思路改进:优化代码书写和移动思路
-
思路
依旧是逆向双指针。但是在思路二的代码实现中对nums1和nums2遍历结束做了单独的判断,当nums1遍历结束后,将nums2放入nums1中;当nums2遍历结束后,将nums1放入nums1中。
由于nums1和nums2中的数据本身就具有有序。
如果nums2结束了,nums1中的数据有剩余,那么他一定满足排序结果,我们不需要对他进行任何移动,直接放在原来的位置就可以了。
如果nums1结束了,nums2中的数据有剩余,我们必须将nums2中的数据转移到nums1中。
-
代码
/**
* invertedDoublePointer的优化
* @param nums1
* @param m
* @param nums2
* @param n
*/
public static void invertedDoublePointer2(int[] nums1, int m, int[] nums2, int n) {
//三个右指针,从右侧逐渐减小;
int l1 = m-1;
int l2 = n-1;
int l3 = m+n-1;
while(l1>=0&&l2>=0){//如果有一个数组遍历结束了就结束
if (nums1[l1]>nums2[l2]){
nums1[l3--] = nums1[l1--];
}else {
nums1[l3--] = nums2[l2--];
}
}
while (l2>=0){//如果nums2中有剩余,就把nums2中的内容移到nums1中
nums1[l3--] = nums2[l2--];
}
}
-
分析
时间复杂度:O(m+n)。
空间复杂度:O(1),原地移动元素,无需额外空间。
-
结果