-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathMerge Sorted Array.java
More file actions
29 lines (26 loc) · 847 Bytes
/
Copy pathMerge Sorted Array.java
File metadata and controls
29 lines (26 loc) · 847 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
/*
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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
*/
public class Solution {
public void merge(int A[], int m, int B[], int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
while (m > 0 && n > 0) {
if (A[m - 1] > B[n - 1]) {
A[m + n - 1] = A[m - 1];
m--;
} else {
A[m + n - 1] = B[n - 1];
n--;
}
}
if (n > 0) {
while (n > 0) {
A[n - 1] = B[n - 1];
n--;
}
}
}
}