LeetCode OJ 88. Merge Sorted Array

时间:2022-05-31 20:48:39

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 nums1and nums2 are m and n respectively.

【思路】

我们设置两个指针p1和p2分别指向nums1和nums2,如果nums[p1]<=nums[p2],则p1向后移动,否则的话我们在nums2中找到从p2起所有比nums[p1]小的元素的个数movlen,然后把nums1中p1后(包含p1)的元素向后移动movlen,然后在nums1空出的位置复制nums2中从p2起movlen个元素。p1+=movlen,p2+=movlen。

如果循环结束后nums2中还有元素没有被遍历到,则把这些元素直接加到nums1中。代码如下:

 public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
if(nums1==null||nums2==null||m+n>nums1.length) return; int totalen = m + n;
int p1 = 0;
int p2 = 0;
int movelen = 0;
while(p1 < m && p2 < n){
if(nums1[p1] <= nums2[p2]) p1++; //nums1指针向后移动
else{
movelen++;
for(int i = p2 + 1; i < n; i++){ //找到nums2中所有比nums1[p1]小的元素的个数
if(nums2[i] < nums1[p1]) movelen++;
else break;
}
for(int j = m - 1; j >= p1; j--){ //nusm1中的元素向后移动
nums1[j+movelen] = nums1[j];
}
for(int k = 0; k<movelen; k++){ //拷贝nums2中的元素
nums1[p1+k] = nums2[p2 + k];
}
p1 = p1 + movelen;
m = m + movelen; //nums1的长度增加
p2 = p2 + movelen;
movelen = 0;
}
}
while(p2 < n){ //如果nums2中还有元素则直接加到nums1的末尾
nums1[m++] = nums2[p2++];
}
}
}