[LeetCode] Merge Sorted Array

뚜니어리·2023년 8월 24일
0

알고리즘

목록 보기
4/5
post-thumbnail

📚 문제

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.

📍 예시

** 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.

첫 느낌 .. 일단 처음 보는 영어문제라서 당황했다 ...
바로 해석 시작..


✏️ 문제 해석

오름차순으로 정렬 된 정수 배열 nums1, nums2 가 있다.
정수 m, n이 주어지눈데, 각각 nums1, nums2의 요소의 갯수이다.
-> 주어진 요소의 갯수가 아니라 반환해야하는 요소의 갯수인듯...

두 배열을 하나의 배열로 합쳐라. 오름차순 정렬 필요. + 자르지 않고 합치기

마지막 정렬된 배열은 함수로 반환되지 않고, nums1에 포함되어 정렬되서 반환되어야한다.

nums1은 m + n의 길이를 가지며,
여기서 처음 m개의 요소는 병합해야 할 요소를 나타내고,

마지막 n개의 요소는 0으로 설정되어 무시한다.
nums2는 n의 길이를 가집니다.


💡 내가 생각한 풀이 - 1

1. nums1을 m개의 갯수만큼 그대로 유지하고, 그 뒤에는 0으로 변경
2. nums2 를 n개의 갯수만큼 그대로 유지하고, 그 뒤에는 0으로 변경
3. nums1 을 [:m]으로 m개만 꺼내서 nums1로, nums2를 [:n]개만 꺼내서 다시 저장
4. 배열들을 합쳐서 nums1로 저장: nums1 = nums1 + nums2
5. 합친 배열 num1을 [:m+n]까지 자르기
6. 마지막 nums1 를 sort로 오름차순 정렬
for i in range(m, len(nums1)):
	nums1[i] = 0
print("1 :", nums1)

for j in range(n, len(nums2)):
	nums2[i] = 0
print("2 :", nums2)

nums1 = nums1[:m]
nums2 = nums2[:n]
print("3 :", nums1, nums2)

nums1 = nums1+nums2
print("4 :", nums1)

nums1 = nums1[:m+n]
print("5 :", nums1)

nums1.sort()
print("6 :", nums1)

vscode

leetcode

다 잘 나오는데...
왜 .. 실패가 뜨는거지...


💡 내가 생각한 풀이 - 2

1. nums1에서 0이 있다면 0을 제거하기
2. nums2에서 0이 있다면 0을 제거하기
3. nums1을 nums1+nums2로 재선언
4. nums1 을 m+n까지 자르기
5. nums1을 자른 후에 오름차순으로 정렬
nums1 = [num for num in nums1 if num != 0]
print("1 :" , nums1)

nums2 = [num2 for num2 in nums2 if num2 != 0]
print("2 :", nums2)

nums1 = nums1+nums2
print("3 :", nums1)

nums1 = nums1[:m+n]
print("4 :", nums1)

nums1.sort()
print("5 :", nums1)

vscode

leetcode

하지만 결과는.. 여전히...


💡 도움을 받은 풀이

1. nums1을 m까지 자른다.
2. nums2를 n까지 자른다.
3. nums1을 nums1+nums2를 합친 배열로 다시 저장한다.
4. nums1을 오름차순으로 정렬한다.
nums1 = nums1[0:m]
print("1 :", nums1)

nums2 = nums2[0:n]
print("2 :", nums2)

nums1 = nums1+nums2
print("3 :", nums1)

nums1.sort()
print("4 :", nums1)

vscode

leetcode

결과..

세 개 다 case2 만 성공하고 1,3은 계속 실패한다...

여러개 검색해 본 결과..
nums1를 재선언하면 안된다고 하는데.. 음.. 음 ... 나는 왜 재선언을 제거해도 똑같지... 일단 ... 좀 더 생각해보기...

💡 드디어 찾은 답

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        # nums1[:] -> 재선언으로 안받아들임

        del(nums1[m:])
        nums1[0:m] += nums2[0:n]
        nums1.sort()

내 코드보다 ... 많이 줄었는데 !
이렇게 답이 나오다니..

🪄 리스트 컴프리헨션(List Comprension)

리스트 컴프리헨션이란 리스트를 직관적으로 볼 수 있도록 생성하는 방법
대괄호로 감싸고 내부에 for문과 if문을 사용하여 반복하며 조건에만 만족하는 것을 리스트로 생성
리스트 컴프리헨션을 사용하는 이유는 직관적으로 확인가능, 속도가 빠름

> 도움 주실 분.. 환영합니다...

profile
삽질과 저장소의 그 중간

0개의 댓글