题目描述:
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 and nums2 are m and n respectively.
merge两个排序的数组,要求把数组2:nums2 合并到数组1:nums1中,可以假设nums1中有足够的空间(末尾)
思路:
1. nums1和nums2从后往前遍历,取最大的那个放nums1的最后
2. 如果nums2中有没有遍历完的,继续放完。
实现代码:public class Solution {
public void Merge(int[] nums1, int m, int[] nums2, int n) {
var i = m ;
var j = n ;
// merge nums2 into nums1
while(i > 0 && j > 0){
// get the bigger one and put at last vacancy
if(nums1[i - 1] > nums2[j - 1]){
nums1[i+j - 1] = nums1[i-1];
i--;
}else{
nums1[i+j - 1] = nums2[j-1];
j--;
}
}
j--;
while(j >= 0){
nums1[i+j] = nums2[j];
j--;
}
}
}