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.
思路:创建一个新数组ans[k],设置i,j分别是nums1,nums2的下标,将nums1[i]与nums2[j]中较小的放入中,同时将k++,和相应的坐标++;
当一个数组遍历完时再把剩下没遍历完的数组剩下的部分放入ans后面。
代码如下(已通过leetcode)
public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] temp= new int[m+n];
int i=0,j=0,k=0;
while(i<m&&j<n) {
if(nums1[i]<nums2[j]) {
temp[k]=nums1[i];
i++;
} else {
temp[k]=nums2[j];
j++;
}
k++;
}
while(i<m){
temp[k]=nums1[i];
i++;
k++;
}
while(j<n) {
temp[k]=nums2[j];
j++;
k++;
}
for(int p=0;p<temp.length;p++)
nums1[p]=temp[p];
}
}