Merge Sorted Array (Easy)

Description

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 n respectively.

Analysis

两个有序数组的合并,时间复杂度O(m+n)

My Solution

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
//C++
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int x = m-1,y = n-1, z = m+n-1;
while(x>=0||y>=0)
{
if(x<0)
{
A[z] = B[y];
y--,z--;
}
else if(y<0)
{
A[z]=A[x];
x-- , z--;
}
else if(A[x]>=B[y])
{
A[z]=A[x];
z--,x--;
}
else if(A[x]<B[y])
{
A[z]=B[y];
z--,y--;
}
}
}
};