-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-sorted-array.java
More file actions
30 lines (28 loc) · 935 Bytes
/
Copy pathmerge-sorted-array.java
File metadata and controls
30 lines (28 loc) · 935 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
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
Queue<Integer> queue = new LinkedList<Integer>();
int indexNums1 = 0;
int indexNums2 = 0;
if (n == 0) {
return;
}
for (int i = 0; i < (m+n); i++) {
if (indexNums2 >= n || !queue.isEmpty() && (queue.peek() < nums2[indexNums2])) {
if (indexNums1 < m) {
queue.add(nums1[i]);
indexNums1++;
}
nums1[i] = queue.poll();
} else if (nums1[i] <= nums2[indexNums2] && indexNums1 < m) {
indexNums1++;
} else {
if (indexNums1 < m) {
queue.add(nums1[i]);
indexNums1++;
}
nums1[i] = nums2[indexNums2];
indexNums2++;
}
}
}
}