
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.
Follow up: Can you come up with an algorithm that runs in O(m + n) time?
병합 정렬의 merge 함수를 구현하는 문제에요.
다만 조건이 첫번째 파라미터인 nums1에 정답을 초기화하라고 합니다.
저 같은 경우엔 nums1 변수를 깊은 복사한 배열과 nums2와 비교하고 이를 nums1에 초기화하는 방식을 전개했습니다.
class Solution {
public void insert(int[] nums, int number, int insertAt){
for(int nIndex2 = nums.length - 1; nIndex2 > insertAt; --nIndex2){
nums[nIndex2] = nums[nIndex2 - 1];
}
nums[insertAt] = number;
}
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i = 0, i2 = 0; i < nums1.length && i2 < n; ++i){
if(i >= m && nums1[i] == 0){
nums1[i] = nums2[i2++];
continue;
}
if(nums1[i] >= nums2[i2]){
insert(nums1, nums2[i2++], i);
}
}
}
}