https://leetcode.com/problems/merge-sorted-array/?envType=study-plan-v2&envId=top-interview-150
Merge Sorted Array - LeetCode
Can you solve this real interview question? Merge Sorted Array - 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 an
leetcode.com
📌 - 처음 생각한 풀이
- num1 배열과 num2 배열을 비교하면서 더 큰 값을 num1의 배열 뒤쪽에 넣어준다.
풀이하는 방식은 투 포인터와 비슷한 방식으로 m,n으로 비교를 하면서 해당하는 값을 크기에 맞게 넣어주는 것은 맞음
📌- 풀이
- num1 배열과 num2 배열을 비교하면서 더 큰 값을 num1의 배열 뒤쪽에 넣어준다.
- n이 0일때와 m이 0일때를 예외처리
n이 0이거나 m이 0일때 indexError가 발생하므로 해당 부분을 예외처리 해줘야 한다.
다음 문제는 코드를 더 깔끔하게 만들도록 해야할듯.
🔥 - Java 코드
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for(int i=nums1.length-1 ;i>=0 ; i-- ){
if(m ==0 ){
nums1[i] = nums2[n-1];
n--;
continue;
}else if(n==0){
nums1[i] = nums1[m-1];
m--;
continue;
}
if(nums1[m-1] >= nums2[n-1]){
nums1[i] = nums1[m-1];
m--;
}else if(nums1[m-1] < nums2[n-1]){
nums1[i] = nums2[n-1];
n--;
}
}
System.out.println(Arrays.toString(nums1));
}
}