Skip to content

Commit 84dd019

Browse files
committed
Added Merge Sorted Array - Easy
1 parent b83034b commit 84dd019

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Time: O(n + m)
3+
* Space: O(1)
4+
*/
5+
class Solution {
6+
public void merge(int[] nums1, int m, int[] nums2, int n) {
7+
int i = m + n - 1;
8+
int p1 = m - 1;
9+
int p2 = n - 1;
10+
11+
while (p1 >= 0 && p2 >= 0) {
12+
if (nums1[p1] > nums2[p2]) {
13+
// Set nums1[i] to the bigger number and decrement the pointers
14+
nums1[i--] = nums1[p1--];
15+
} else {
16+
// Set nums1[i] to the bigger number and decrement the pointers
17+
nums1[i--] = nums2[p2--];
18+
}
19+
}
20+
// While there are left over numbers from nums1, insert them into the final merged array
21+
while (p1 >= 0) {
22+
nums1[i--] = nums1[p1--];
23+
}
24+
// While there are left over numbers from nums2, insert them into the final merged array
25+
while (p2 >= 0) {
26+
nums1[i--] = nums2[p2--];
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)