-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSortedArrays.cpp
58 lines (51 loc) · 1.14 KB
/
MergeSortedArrays.cpp
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
//
// MergeSortedArrays.cpp
//
//
// Created by 廷芳 杜 on 7/9/13.
// Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//
#include <iostream>
ass Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if( n == 0 ) return;
if( m == 0 )
{
for( int i = 0 ; i < n ; i++ )
A[i] = B[i];
}
int ptA = m-1;
int ptB = n-1;
int pt = m+n-1;
while( ptA>=0 && ptB>=0 )
{
if( A[ptA] < B[ptB] )
{
A[pt] = B[ptB];
ptB--;
pt--;
}
else
{
A[pt] = A[ptA];
ptA--;
pt--;
}
}
if( ptA>= 0 )
{
while( pt>=0 )
A[pt--] = A[ptA--];
return;
}
else
{
while( pt>=0 )
A[pt--] = B[ptB--];
return;
}
}
};