简繁EN

LeetCodeNo. 022

[LeetCode with Python] 88. Merge Sorted Array

Contents

Problem

Problem page: https://leetcode.com/problems/merge-sorted-array/
Topics: Array, Two Pointers
Difficulty: Easy
Similar problems: (E) Merge Two Sorted Lists

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is > greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.


Analysis

Merge a sorted array B into another sorted array A. If we start the merge at the front, we have to shift all the remaining elements of A each time, so that's not ideal. We can be clever here and start the merge at the ends of both arrays so we don't have to shift large blocks of elements.


Code

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
class Solution:
# @param A a list of integers
# @param m an integer, length of A
# @param B a list of integers
# @param n an integer, length of B
# @return nothing
def merge(self, A, m, B, n):
if 0 == n:
return A
if 0 == m:
for i in range(0, n):
A[i] = B[i]
return A

index = m + n - 1
indexA = m - 1
indexB = n - 1
while indexA >= 0 and indexB >= 0:
if A[indexA] >= B[indexB]:
A[index] = A[indexA]
index -= 1
indexA -= 1
else:
A[index] = B[indexB]
index -= 1
indexB -= 1
if indexA >= 0:
pass
else:
for i in range(0, indexB + 1):
A[i] = B[i]

Article link: https://xnerv.wang/en/leetcode-merge-sorted-array/