Skip to content

Commit 0adf523

Browse files
committed
D. J.:
- Added leetcode problem and solution for 88. Merge Sorted Array
1 parent a12abe6 commit 0adf523

File tree

4 files changed

+45
-0
lines changed

4 files changed

+45
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
6+
"""
7+
You are given two integer arrays nums1 and nums2, sorted in non-decreasing order,
8+
and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
9+
10+
Merge nums1 and nums2 into a single array sorted in non-decreasing order.
11+
12+
The final sorted array should not be returned by the function, but instead be stored inside the array nums1.
13+
To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged,
14+
and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
15+
"""
16+
midx = m - 1
17+
nidx = n - 1
18+
right = m + n - 1
19+
20+
while nidx >= 0:
21+
if midx >= 0 and nums1[midx] > nums2[nidx]:
22+
nums1[right] = nums1[midx]
23+
midx -= 1
24+
else:
25+
nums1[right] = nums2[nidx]
26+
nidx -= 1
27+
right -= 1

awesome_python_leetcode/__init__.py

Whitespace-only changes.

tests/__init__.py

Whitespace-only changes.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._88_merge_sorted_array import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums1", "m", "nums2", "n", "expected"],
10+
argvalues=[
11+
([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3, [1, 2, 2, 3, 5, 6]),
12+
([1], 1, [], 0, [1]),
13+
([0], 0, [1], 1, [1]),
14+
],
15+
)
16+
def test_func(nums1: List[int], m: int, nums2: List[int], n: int, expected: List[int]):
17+
Solution().merge(nums1, m, nums2, n)
18+
assert nums1 == expected

0 commit comments

Comments
 (0)