-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode_MergeSortedArray.cpp
More file actions
61 lines (56 loc) · 987 Bytes
/
Copy pathleetcode_MergeSortedArray.cpp
File metadata and controls
61 lines (56 loc) · 987 Bytes
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
59
60
61
//Method1: AC
//Use temp array,time complexity is O(2(m+n))=O(m+n)
//space complexity is O(m+n)
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int i=0,j=0,count=0;
int *c=new int[m+n];
while(i<m || j<n){
if( i<m && j<n){
if(A[i]<B[j]){
c[count++]=A[i++];
}
else
c[count++]=B[j++];
}
else if(i<m){
c[count++]=A[i++];
}
else{
c[count++]=B[j++];
}
}
for(i=0; i<count; ++i)
A[i]=c[i];
delete []c;
}
};
//Method2: TLE
//Don't use temp array, worst time complexity is O(mn+m)=O(mn)
//but space complexity is O(1)
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int i=0,j=0,count=0,k;
while(i<m || j<n){
if( i<m && j<n){
if(A[count]<=B[j]){
count++;
i++;
}
else{
for(k=m-i; k>=0; --k)
A[count+k+1]=A[count+k];
A[count++]=B[j++];
}
}
else if(i<m){
continue;
}
else{
A[count++]=B[j++];
}
}
}
};