java: add «88. Merge Sorted Array»

URL:	https://leetcode.com/problems/merge-sorted-array/
This commit is contained in:
Matej Focko 2025-01-02 09:31:27 +01:00
parent ec2d7fe842
commit 8ecf9fb8d8
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,25 @@
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
// Shift numbers to right
for (int i = m - 1, k = nums1.length - 1; i >= 0; --i, --k) {
nums1[k] = nums1[i];
}
// Merge them
int j = 0, k = 0;
for (int i = nums1.length - m; i < nums1.length && j < n; ++k) {
if (nums1[i] < nums2[j]) {
nums1[k] = nums1[i];
++i;
} else {
nums1[k] = nums2[j];
++j;
}
}
// Add the remainder
for (; j < n; ++j, ++k) {
nums1[k] = nums2[j];
}
}
}