LeetCode - 88. Merge Sorted Array(Array, Two Pointers, Sorting)

YAMAMAMO·2022년 1월 25일
0

LeetCode

목록 보기
5/100

문제

https://leetcode.com/problems/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 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과 nums2가 주어지며, 각각 nums1과 nums2의 원소 수를 나타내는 두 개의 정수 m과 n이 주어집니다.
nums1과 nums2를 감소하지 않는 순서로 정렬된 단일 배열로 병합합니다.
마지막으로 정렬된 배열은 함수에 의해 반환되지 않고 배열 번호1 안에 저장되어야 합니다. 이를 수용하기 위해 nums1은 m + n의 길이를 가지며, 여기서 첫 번째 m 원소는 병합되어야 할 원소를 나타내고 마지막 n 원소는 0으로 설정되며 무시되어야 한다. nums2의 길이는 n입니다.

Example 1:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.

Example 2:

Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
Explanation: The arrays we are merging are [1] and [].
The result of the merge is [1].

Example 3:

Input: nums1 = [0], m = 0, nums2 = [1], n = 1
Output: [1]
Explanation: The arrays we are merging are [] and [1].
The result of the merge is [1].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.

풀이

자바입니다.
1. nums2 의 포지션값 int j 변수 선언.
2. i<m+n 이 될때까지 반복한다.
3. j<n, nums1[i]==0 을 만족할 때 nums1[i] 에 nums2[j] 값을 넣는다.
4. j++ 한다.
5. Arrays.sort() 를 사용해서 nums1 을 오름차순으로 정렬한다.

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int j = 0;
        for(int i=0; i<m+n; i++){
            if(j<n&&nums1[i]==0){
                nums1[i]=nums2[j];
                j++;
            }
        }
        Arrays.sort(nums1);
    }
}
profile
안드로이드 개발자

0개의 댓글