[LeetCode] Top Interview 150 Problems Solving # 88 Merge Sorted Array
Understanding the Problem
When I saw the sample codes and the problem, I had no clue what I was supposed to do with these. But anyways the problem explanation went, I was given two arrays with two numbers as parameters like,
# sample
nums1 = [1, 2, 3, 0, 0, 0]
m = 3
nums2 = [2, 5, 6]
n = 3
m
indicates the first m
numbers to be used in the nums1, and n indicates the length of the nums2. I needed to combine these two lists but nums1 needed further processing with slicing. in this sample nums should be [1, 2, 3]
as it only needs the first 3 numbers just like m
says.
After combining it should be sorted ascending, thus the output should be [1, 2, 2, 3, 5, 6].
Approach
The problem was obvious and I was ready to solve it but the problem was how to return the list. The sample code started with,
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.
"""
which, I was stunned a little bit with the state “Do not return anything”, but figured out that it was the matter of touching nums1 list directly.
First I went slicing nums1 with the length of m, then just simply added nums2 into nums1
Solution
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[:] = nums1[:m]
if len(nums2) != 0:
nums1[:] += nums2[:]
nums1.sort()
Yip, it is not the best, but I did my best. If nums2 was not empty I added it to nums1.
Reflection
It was not that difficult for me to solve it but I did not know exectly how to change values of the list given through parameter. It just did not work when I went nums1 = nums1[:m]
but instead it had to be used with slicing like nums1[:] = nums1[:m]
.