## 龙之梦

Stay Hungry, Stay Foolish

# LeetCode 88 — Merge Sorted Array（C++ Java Python）

Given two sorted integer arrays A and B, merge B into A as one sorted array.

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

从后向前考虑。如果A中的先遍历完，应把B中剩下的元素复制到A中。
C++实现：
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
if(n == 0)
{
return;
}

int idx = m + n - 1;
int i = m - 1;
int j = n - 1;

while(i >= 0 && j >= 0)
{
if(A[i] >= B[j])
{
A[idx--] = A[i--];
}
else
{
A[idx--] = B[j--];
}
}

if(i == -1)
{
while(j >= 0)
{
A[j] = B[j];
j--;
}
}
}
};
Java实现：
public class Solution {
public void merge(int A[], int m, int B[], int n) {
int idx = m + n - 1;
int i = m - 1;
int j = n - 1;

while (i >= 0 && j >= 0) {
if (A[i] >= B[j]) {
A[idx--] = A[i--];
} else {
A[idx--] = B[j--];
}
}

if (i == -1) {
while (j >= 0) {
A[j] = B[j];
j--;
}
}
}
}
Python实现：
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):
idx = m + n - 1
i = m - 1
j = n - 1

while i >= 0 and j >= 0:
if A[i] >= B[j]:
A[idx] = A[i]
i -= 1
else:
A[idx] = B[j]
j -= 1

idx -= 1

if i == -1:
while j >= 0:
A[j] = B[j]
j -= 1
感谢阅读，欢迎评论！

#### 【leetcode】88. Merge Sorted Array（Python & C++）

2017-09-05 21:39:01

#### leetcode88题 题解 翻译 C语言版 Python版

2016-04-19 19:48:50

#### leetcode88 python 合并两个有序数组

2018-05-06 15:13:23

#### leetcode python 简单难度 解答版本(持续更新)

2017-12-20 16:56:29

#### LeetCode88——Merge Sorted Array

2015-01-14 16:10:41

#### leetcode 88 Merge Sorted Array

2015-06-24 22:47:51

#### 88. Merge Sorted Array [easy] (Python)

2016-06-15 13:54:39

#### Merge Sorted Array -- LeetCode

2014-02-22 23:27:09

#### LeetCode（88）Merge Sorted Array

2015-08-20 17:33:59