Skip to content

Commit e3e7487

Browse files
authored
Update 088. Merge Sorted Array.java
1 parent ef2b01e commit e3e7487

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

088. Merge Sorted Array.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,22 @@ public void merge(int[] nums1, int m, int[] nums2, int n) {
1515
return;
1616
}
1717
}
18+
19+
// even more succint
20+
// 1st loop: either i runs out first or j runs out first
21+
// - if i runs out first, finish with elems from j
22+
// - if j runs out first, 2nd loop won't be executed, won't need to
23+
// move the remaining elements from first (also resulting) array either
24+
public class Solution {
25+
public void merge(int[] nums1, int m, int[] nums2, int n) {
26+
int c = m + n, i = m - 1, j = n - 1;
27+
28+
while (i >= 0 && j >= 0)
29+
nums1[--c] = nums1[i] <= nums2[j] ? nums2[j--] : nums1[i--];
30+
31+
while (j >= 0)
32+
nums1[--c] = nums2[j--];
33+
34+
return;
35+
}
36+
}

0 commit comments

Comments
 (0)