Skip to content

Commit 7c74657

Browse files
committed
regular leetcode
1 parent 59c25c1 commit 7c74657

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

088._merge_sorted_array.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
###88. Merge Sorted Array
2+
3+
4+
题目:
5+
<https://leetcode.com/problems/merge-sorted-array/>
6+
7+
8+
难度 : Easy
9+
10+
给的数组可能是这样的
11+
12+
nums1 : [0]
13+
m : 0
14+
nums2 : [1]
15+
n : 1
16+
17+
18+
设置指针p = m + n -1, p1 = m - 1, p2 = n - 1
19+
20+
从末端开始,哪个数更大就放末端,两个指针都走到-1才算走完,问题可能出现在p1走完但是p2还没走完,所以添加一个多的loop来检查,想之上的例子就可以理解
21+
22+
23+
AC代码
24+
25+
26+
```
27+
class Solution(object):
28+
def merge(self, nums1, m, nums2, n):
29+
"""
30+
:type nums1: List[int]
31+
:type m: int
32+
:type nums2: List[int]
33+
:type n: int
34+
:rtype: void Do not return anything, modify nums1 in-place instead.
35+
"""
36+
p = m + n -1
37+
p1 = m - 1
38+
p2 = n - 1
39+
while p2 >= 0 and p1 >= 0 :
40+
if nums2[p2] > nums1[p1]:
41+
nums1[p] = nums2[p2]
42+
p2 -= 1
43+
else:
44+
nums1[p] = nums1[p1]
45+
p1 -= 1
46+
p -= 1
47+
48+
49+
50+
for i in range(p2,-1,-1):
51+
nums1[p] = nums2[i]
52+
p -= 1
53+
54+
```

0 commit comments

Comments
 (0)