Skip to content

Commit 0557ff4

Browse files
committed
feat: add arr merge sorted array
1 parent b3cfd71 commit 0557ff4

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

arr.merge-sorted-array.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
88. 合并两个有序数组
6+
https://leetcode-cn.com/problems/merge-sorted-array/
7+
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组
8+
"""
9+
# 双指针
10+
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
11+
m -= 1
12+
n -= 1
13+
while n >= 0:
14+
if m >= 0 and nums1[m] > nums2[n]:
15+
nums1[n + m + 1] = nums1[m]
16+
m -= 1
17+
else:
18+
nums1[n + m + 1] = nums2[n]
19+
n -= 1
20+
21+
# 系统排序
22+
def mergeBySystem(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
23+
nums1[:] = sorted(nums1[:m] + nums2)
24+
25+
26+
27+
28+
so = Solution()
29+
nums = [0, 1, 1, 2, 3, 5, 7]
30+
nums1 = [1, 2, 4]
31+
so.merge(nums, 4, nums1, 3)
32+
print(nums)
33+

0 commit comments

Comments
 (0)