33/**
44 * Description: https://leetcode.com/problems/median-of-two-sorted-arrays
55 * Difficulty: Hard
6- * Time complexity: O(log min(m, n))
7- * Space complexity: O(1)
86 */
97public class MedianOfTwoSortedArrays {
108
11- public double findMedianSortedArraysV1 (int [] small , int [] large ) {
9+ /**
10+ * Time complexity: O(log min(m, n))
11+ * Space complexity: O(1)
12+ */
13+ public double findMedianSortedArraysViaBinarySearchV1 (int [] small , int [] large ) {
1214 if (small .length > large .length ) {
13- return findMedianSortedArraysV1 (large , small );
15+ return findMedianSortedArraysViaBinarySearchV1 (large , small );
1416 }
1517
1618 int total = small .length + large .length ;
@@ -43,9 +45,13 @@ public double findMedianSortedArraysV1(int[] small, int[] large) {
4345 throw new RuntimeException ();
4446 }
4547
46- public double findMedianSortedArraysV2 (int [] small , int [] large ) {
48+ /**
49+ * Time complexity: O(log min(m, n))
50+ * Space complexity: O(1)
51+ */
52+ public double findMedianSortedArraysViaBinarySearchV2 (int [] small , int [] large ) {
4753 if (small .length > large .length ) {
48- return findMedianSortedArraysV2 (large , small );
54+ return findMedianSortedArraysViaBinarySearchV2 (large , small );
4955 }
5056
5157 int total = small .length + large .length ;
@@ -72,4 +78,41 @@ public double findMedianSortedArraysV2(int[] small, int[] large) {
7278
7379 throw new RuntimeException ();
7480 }
81+
82+ /**
83+ * Time complexity: O(m + n)
84+ * Space complexity: O(m + n)
85+ */
86+ public double findMedianSortedArraysViaMerge (int [] first , int [] second ) {
87+ int [] merged = merge (first , second );
88+ int length = merged .length ;
89+ return length % 2 == 0
90+ ? (merged [length / 2 - 1 ] + merged [length / 2 ]) / 2.0
91+ : (double ) merged [length / 2 ];
92+ }
93+
94+ private int [] merge (int [] first , int [] second ) {
95+ int [] merged = new int [first .length + second .length ];
96+
97+ int i = 0 ;
98+ int j = 0 ;
99+ int k = 0 ;
100+ while (i < first .length && j < second .length ) {
101+ if (first [i ] <= second [j ]) {
102+ merged [k ++] = first [i ++];
103+ } else {
104+ merged [k ++] = second [j ++];
105+ }
106+ }
107+
108+ while (i < first .length ) {
109+ merged [k ++] = first [i ++];
110+ }
111+
112+ while (j < second .length ) {
113+ merged [k ++] = second [j ++];
114+ }
115+
116+ return merged ;
117+ }
75118}
0 commit comments