Skip to content

Commit a541cf4

Browse files
authored
Update 04. Median of Two Sorted Arrays.py
1 parent b53e3ef commit a541cf4

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed

11_Binary-Search/04. Median of Two Sorted Arrays.py

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,43 @@
11
# https://leetcode.com/problems/median-of-two-sorted-arrays/
2-
# https://www.youtube.com/watch?v=NTop3VTjmxk
32

3+
# -------------------- Method 1 --------- NOT Optimised O(N) Time----------------
4+
class Solution:
5+
def findMedianSortedArrays(self, nums1, nums2):
6+
n1 = len(nums1); n2 = len(nums2)
7+
mid = (n1 + n2) // 2
8+
i = 0; j = 0
9+
val, preVal = 0, 0
10+
11+
for k in range(mid+1):
12+
if i < n1 and j < n2:
13+
if nums1[i] <= nums2[j]:
14+
val = nums1[i]
15+
i += 1
16+
else:
17+
val = nums2[j]
18+
j += 1
19+
elif i < n1:
20+
val = nums1[i]
21+
i += 1
22+
else:
23+
val = nums2[j]
24+
j += 1
25+
26+
if k == mid - 1:
27+
preVal = val
28+
29+
if (n1+n2) % 2 == 0:
30+
return (val + preVal) / 2
31+
return float(val)
32+
33+
# Timw: O(N)
34+
# Space: O(1)
35+
36+
37+
38+
# -------------------- Method 2 --------- Optimised O(log(N)) Time----------------
39+
40+
# https://www.youtube.com/watch?v=NTop3VTjmxk
441
class Solution:
542
def findMedianSortedArrays(self, nums1, nums2):
643
n1 = len(nums1); n2 = len(nums2)
@@ -39,10 +76,8 @@ def findMedianSortedArrays(self, nums1, nums2):
3976

4077
return 0.0 # For both empty arrays
4178

42-
43-
4479
'''
45-
Time Complexity: O(min(n1, n2))
80+
Time Complexity: O(log(n1))
4681
Space Complexity: O(1)
4782
'''
4883

@@ -55,4 +90,4 @@ def findMedianSortedArrays(self, nums1, nums2):
5590
5691
Output:
5792
8.00000
58-
'''
93+
'''

0 commit comments

Comments
 (0)