[LeetCode][Java] Merge Sorted Array

최지수·2021년 11월 28일
0

Algorithm

목록 보기
31/77
post-thumbnail

문제

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.

제한사항

  • nums1.length == m + n
  • nums2.length == n
  • 0 <= m, n <= 200
  • 1 <= m + n <= 200
  • 109-10^9 <= nums1[i], nums2[j] <= 10910^9

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);
            }
        }
    }
}
profile
#행복 #도전 #지속성

0개의 댓글