From 8ecf9fb8d8b54d004e8cd65cef4571fbcc8f0597 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Thu, 2 Jan 2025 09:31:27 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB88.=20Merge=20Sorted=20Arra?= =?UTF-8?q?y=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit URL: https://leetcode.com/problems/merge-sorted-array/ --- java/merge-sorted-array.java | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 java/merge-sorted-array.java diff --git a/java/merge-sorted-array.java b/java/merge-sorted-array.java new file mode 100644 index 0000000..65fcf47 --- /dev/null +++ b/java/merge-sorted-array.java @@ -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]; + } + } +}