88. Merge Sorted Array
描述:
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.
我的思路:
这道题目比较简单,主要是要注意合并两个数组的时候,如果是从前往后复制每个数字的话需要重复移动数字多次,效率低下。所以我们从后往前复制,这样就能减少移动或复制次数,从而提高效率。
我的解决:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
//这里需要注意的是,m和n均为两个数组的实际上的元素个数,因为nums1有足够的空间,所以切记在此处m是不等于nums1.length的!!!
//实际上,nums1.length应该是大于或等于m+n的。
int p1 = m - 1;
int p2 = n -1;
int index = m + n - 1;
while(p1 >= 0 && p2 >= 0){
if(nums1[p1] > nums2[p2]){
nums1[index --] = nums1[p1 --];
}
else
nums1[index --] = nums2[p2 --];
}
while(p2 >= 0){
nums1[index --] = nums2[p2 --];
}
}
}