https://leetcode-cn.com/problems/merge-sorted-array/
我的写法:
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] nums3 = new int[m + n];
int i=0,j=0, k=0;
if(nums2.length == 0) nums3 = nums1;
while(i < m && j<n) {
if(nums1[i] <= nums2[j]) {
nums3[k] = nums1[i];
i++;
}else {
nums3[k] = nums2[j];
j++;
}
k++;
}
while(j < n) {
nums3[k] = nums2[j];
k++;
j++;
}
while(i < m) {
nums3[k] = nums1[i];
k++;
i++;
}
for(int q=0; q<m + n; q++) {
nums1[q] = nums3[q];
}
}
}
还是看下题解的做法吧!
题解1 :
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// Make a copy of nums1.
int [] nums1_copy = new int[m];
System.arraycopy(nums1, 0, nums1_copy, 0, m);
// Two get pointers for nums1_copy and nums2.
int p1 = 0;
int p2 = 0;
// Set pointer for nums1
int p = 0;
// Compare elements from nums1_copy and nums2
// and add the smallest one into nums1.
while ((p1 < m) && (p2 < n))
nums1[p++] = (nums1_copy[p1] < nums2[p2]) ? nums1_copy[p1++] : nums2[p2++];
// if there are still elements to add
if (p1 < m)
System.arraycopy(nums1_copy, p1, nums1, p1 + p2, m + n - p1 - p2);
if (p2 < n)
System.arraycopy(nums2, p2, nums1, p1 + p2, m + n - p1 - p2);
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/merge-sorted-array/solution/he-bing-liang-ge-you-xu-shu-zu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
和我的思路一样,但是调用了系统的复制数组的方法。执行时间比我的快,内存消耗差不多。
《System.arraycopy为什么快》:https://juejin.cn/post/6844903573545811981