-
Notifications
You must be signed in to change notification settings - Fork 15
/
merge-sorted-array-ii.java
58 lines (53 loc) · 1.63 KB
/
merge-sorted-array-ii.java
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
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
int pointer = m + n - 1;
while (pointer >= 0) {
if (m > 0 && n > 0) {
if (A[m - 1] > B[n - 1]) {
A[pointer--] = A[m - 1];
m--;
} else {
A[pointer--] = B[n - 1];
n--;
}
} else {
if (m > 0) {
A[pointer--] = A[m - 1];
m--;
} else {
A[pointer--] = B[n - 1];
n--;
}
}
}
}
}
// To reduce the code:
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
int pointer = m + n - 1;
while (pointer >= 0) {
if ((m > 0 && n > 0 && A[m - 1] > B[n - 1]) || (n <= 0 && m > 0)) {
A[pointer--] = A[m - 1];
m--;
} else if ((m > 0 && n > 0 && A[m - 1] <= B[n - 1]) || (m <= 0&& n > 0)){
A[pointer--] = B[n - 1];
n--;
}
}
}
}