You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
import java.util.Arrays;
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] result = nums1;
nums1 = Arrays.copyOf(nums1, m + n);
int index1 = 0; int index2 = 0; int indexResult = 0;
while (index1 < m && index2 < n) {
if (nums1[index1] <= nums2[index2]) {
result[indexResult] = nums1[index1];
index1++;
} else {
result[indexResult] = nums2[index2];
index2++;
}
indexResult++;
}
if (index1 < m) {
copy(nums1, index1, result, indexResult, m - index1);
}
if (index2 < n) {
copy(nums2, index2, result, indexResult, n - index2);
}
nums1 = result;
}
private void copy(int[] array1, int index1, int[] array2, int index2, int size) {
for (int count = 0; count < size; count++) {
array2[index2 + count] = array1[index1 + count];
}
}
}
System.arraycopy()
를 통해 이미 내가 구현한 copy()
를 더 좋은 성능으로 지원하고 있었다.import java.util.Arrays;
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int[] result = nums1;
nums1 = Arrays.copyOf(nums1, m + n);
int index1 = 0; int index2 = 0; int indexResult = 0;
while (index1 < m && index2 < n) {
if (nums1[index1] <= nums2[index2]) {
result[indexResult] = nums1[index1];
index1++;
} else {
result[indexResult] = nums2[index2];
index2++;
}
indexResult++;
}
if (index1 < m) {
System.arraycopy(nums1, index1, result, indexResult, m - index1);
}
if (index2 < n) {
System.arraycopy(nums2, index2, result, indexResult, n - index2);
}
nums1 = result;
}
}
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;
while (j >= 0) {
if (i >= 0 && nums1[i] > nums2[j]) {
nums1[k--] = nums1[i--];
} else {
nums1[k--] = nums2[j--];
}
}
}
}