Skip to content

Commit 583265e

Browse files
committed
【新增】leetcode-88. 合并两个有序数组
1 parent 2f9d5a8 commit 583265e

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

run_leetcode/088_merge_two_list.py

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env python
2+
# -*- coding: UTF-8 -*-
3+
# @Time : 2020/3/16 16:18
4+
# @Software: PyCharm
5+
# @Author : https://github.com/Valuebai/
6+
"""
7+
88. 合并两个有序数组
8+
~~~~~~~~~~~~~~~
9+
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 num1 成为一个有序数组。
10+
 
11+
说明:
12+
1. 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
13+
2. 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。  
14+
15+
示例:
16+
17+
输入:
18+
nums1 = [1,2,3,0,0,0], m = 3
19+
nums2 = [2,5,6], n = 3
20+
21+
输出: [1,2,2,3,5,6]
22+
"""
23+
24+
25+
def mergeTwoPointers_first(nums1, m, nums2, n):
26+
"""
27+
方法二 : 双指针 / 从前往后
28+
29+
直觉,一般而言,对于有序数组可以通过 双指针法 达到O(n + m)O(n+m)的时间复杂度。
30+
最直接的算法实现是将指针p1 置为 nums1的开头, p2为 nums2的开头,在每一步将最小值放入输出数组中。
31+
由于 nums1 是用于输出的数组,需要将nums1中的前m个元素放在其他地方,也就需要 O(m)O(m) 的空间复杂度。
32+
33+
复杂度分析
34+
- 时间复杂度 : O(n + m)O(n+m)。
35+
- 空间复杂度 : O(m)O(m)。
36+
37+
:type nums1: List[int]
38+
:type m: int
39+
:type nums2: List[int]
40+
:type n: int
41+
:rtype: void Do not return anything, modify nums1 in-place instead.
42+
"""
43+
# Make a copy of nums1.
44+
nums1_copy = nums1[:m]
45+
nums1[:] = []
46+
47+
# Two get pointers for nums1_copy and nums2.
48+
p1 = 0
49+
p2 = 0
50+
51+
# Compare elements from nums1_copy and nums2
52+
# and add the smallest one into nums1.
53+
while p1 < m and p2 < n:
54+
if nums1_copy[p1] < nums2[p2]:
55+
nums1.append(nums1_copy[p1])
56+
p1 += 1
57+
else:
58+
nums1.append(nums2[p2])
59+
p2 += 1
60+
61+
# if there are still elements to add
62+
if p1 < m:
63+
nums1[p1 + p2:] = nums1[p1:]
64+
if p2 < n:
65+
nums1[p1 + p2:] = nums2[p2:]
66+
67+
print(nums1)
68+
69+
70+
def merge(nums1, m, nums2, n):
71+
"""
72+
复杂度分析
73+
74+
- 时间复杂度 : O((n + m)\log(n + m))O((n+m)log(n+m))。
75+
- 空间复杂度 : O(1)O(1)。
76+
77+
:type nums1: List[int]
78+
:type m: int
79+
:type nums2: List[int]
80+
:type n: int
81+
:rtype: void Do not return anything, modify nums1 in-place instead.
82+
"""
83+
# nums1 = A # 更改 nums1 这一变量名所指向的对象。让 nums1 变量指向 A 所指向的对象
84+
# nums1[:] = A # 对nums1指向的对象赋值。把A变量指向的对象的值逐个copy到nums1指向的对象中并覆盖nums1指向的对象的原来值。
85+
# 详细解释 https://leetcode-cn.com/problems/merge-sorted-array/solution/gelthin-gui-bing-pai-xu-by-gelthin/
86+
nums1[:] = sorted(nums1[:m] + nums2) # sorted返回的是一个新的列表对象
87+
88+
89+
if __name__ == "__main__":
90+
mergeTwoPointers_first(nums1=[1, 2, 3, 0, 0, 0], m=3, nums2=[2, 5, 6], n=3)

0 commit comments

Comments
 (0)