Leetcode88:合并两个有序数组
链接: https://leetcode-cn.com/problems/merge-sorted-array/.
给定两个有序证书数组nums1和nums2,将nums2合并到nums1中,使得nums1成为一个有序数组
说明:
1,初始化nums1和nums2的元素数量分别位m和n;
2,可以假设nums1有足够多的空间来保存nums2的元素
解题思路
显然根据说明2,题目要求的最优解法是应该原地排序。
设定指针 len1 和 len 指向nums1的尾部,设定一个指针len2指向nums2的尾部;
再分别从nums1和nums2开始向前遍历,比较指针指向的元素的大小,因为是从后往前插入,大的那个元素插入数组,同时指针向前进一个。
// An highlighted block
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
//因为m和n分别位数组的长度,所以尾指针应该-1
int len1 = m - 1;
int len2 = n - 1;
int len = m + n - 1;
//当nums1或者nums2有一个遍历完,即退出循环
while(len1 >= 0 && len2 >= 0){
nums1[len--] = nums1[len1]>nums2[len2]?nums1[len1--]:nums2[len2--];
}
//如果此时len2<0.但是len1>=0.
//因为是再nums1的数组原地排序,所以不用再处理
//如果len1<0,那么就把剩下的元素拷贝到nums1中
System.arraycopy(nums2 , 0, nums1 , 0, len2+1);
}
}
关于System.arraycopy()的源码阅读
* @param src the source array.
* @param srcPos starting position in the source array.
* @param dest the destination array.
* @param destPos starting position in the destination data.
* @param length the number of array elements to be copied.
* @exception IndexOutOfBoundsException if copying would cause
* access of data outside array bounds.
* @exception ArrayStoreException if an element in the <code>src</code>
* array could not be stored into the <code>dest</code> array
* because of a type mismatch.
* @exception NullPointerException if either <code>src</code> or
* <code>dest</code> is <code>null</code>.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);