合并两个有序数组是归并排序重要的一环,所以掌握这个算法十分重要。
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] temp = new int[m + n];
int left = 0;
int right = 0;
int index = 0;
while(left < m && right < n){
if(nums1[left] <= nums2[right]){
temp[index] = nums1[left];
left++;
}else{
temp[index] = nums2[right];
right++;
}
index++;
}
while(left < m){
temp[index] = nums1[left];
left++;
index++;
}
while(right < n){
temp[index] = nums2[right];
right++;
index++;
}
for(int i=0; i<m+n; i++){
nums1[i] = temp[i];
}
}
}