-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path88.合并两个有序数组.py
97 lines (93 loc) · 2.41 KB
/
88.合并两个有序数组.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#
# @lc app=leetcode.cn id=88 lang=python3
#
# [88] 合并两个有序数组
#
# https://leetcode.cn/problems/merge-sorted-array/description/
#
# algorithms
# Easy (52.28%)
# Likes: 1427
# Dislikes: 0
# Total Accepted: 657.9K
# Total Submissions: 1.3M
# Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3'
#
# 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2,另有两个整数 m 和 n ,分别表示 nums1 和 nums2 中的元素数目。
#
# 请你 合并 nums2 到 nums1 中,使合并后的数组同样按 非递减顺序 排列。
#
# 注意:最终,合并后数组不应由函数返回,而是存储在数组 nums1 中。为了应对这种情况,nums1 的初始长度为 m + n,其中前 m
# 个元素表示应合并的元素,后 n 个元素为 0 ,应忽略。nums2 的长度为 n 。
#
#
#
# 示例 1:
#
#
# 输入:nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
# 输出:[1,2,2,3,5,6]
# 解释:需要合并 [1,2,3] 和 [2,5,6] 。
# 合并结果是 [1,2,2,3,5,6] ,其中斜体加粗标注的为 nums1 中的元素。
#
#
# 示例 2:
#
#
# 输入:nums1 = [1], m = 1, nums2 = [], n = 0
# 输出:[1]
# 解释:需要合并 [1] 和 [] 。
# 合并结果是 [1] 。
#
#
# 示例 3:
#
#
# 输入:nums1 = [0], m = 0, nums2 = [1], n = 1
# 输出:[1]
# 解释:需要合并的数组是 [] 和 [1] 。
# 合并结果是 [1] 。
# 注意,因为 m = 0 ,所以 nums1 中没有元素。nums1 中仅存的 0 仅仅是为了确保合并结果可以顺利存放到 nums1 中。
#
#
#
#
# 提示:
#
#
# nums1.length == m + n
# nums2.length == n
# 0 <= m, n <= 200
# 1 <= m + n <= 200
# -10^9 <= nums1[i], nums2[j] <= 10^9
#
#
#
#
# 进阶:你可以设计实现一个时间复杂度为 O(m + n) 的算法解决此问题吗?
#
#
# @lc code=start
from requests import put
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.
"""
if not n :
return nums1
i,j=0,0
out = []
while i< m and j <n:
if nums1[i] <= nums2[j]:
out.append(nums1[i])
i+=1
else:
out.append(nums2[j])
j+=1
if i ==n :
out.extend(nums2[j:])
else:
out.extend(nums1[i:m])
nums1 =out
# @lc code=end