diff --git a/JAVA/4-Median-of-Two-Sorted-Array/Solution.java b/JAVA/4-Median-of-Two-Sorted-Array/Solution.java new file mode 100644 index 0000000..ae3402a --- /dev/null +++ b/JAVA/4-Median-of-Two-Sorted-Array/Solution.java @@ -0,0 +1,30 @@ +class Solution { + public double findMedianSortedArrays(int[] nums1, int[] nums2) { + int m = nums1.length; + int n = nums2.length; + int[] merged = new int[m + n]; + + int i = 0, j = 0, k = 0; + + // Merge the two sorted arrays + while(i < m && j < n) { + if(nums1[i] < nums2[j]) { + merged[k++] = nums1[i++]; + } else { + merged[k++] = nums2[j++]; + } + } + + // Copy remaining elements + while(i < m) merged[k++] = nums1[i++]; + while(j < n) merged[k++] = nums2[j++]; + + // Find the median + int total = m + n; + if(total % 2 == 1) { + return merged[total / 2]; + } else { + return (merged[total / 2 - 1] + merged[total / 2]) / 2.0; + } + } +}