-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathMedian_of_Two_Sorted_Arrays.py
More file actions
43 lines (35 loc) · 1.17 KB
/
Median_of_Two_Sorted_Arrays.py
File metadata and controls
43 lines (35 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution:
def findMedianSortedArrays(
self, nums1: List[int], nums2: List[int]
) -> float:
m, n = len(nums1), len(nums2)
p1, p2 = 0, 0
# Get the smaller value between nums1[p1] and nums2[p2].
def get_min():
nonlocal p1, p2
if p1 < m and p2 < n:
if nums1[p1] < nums2[p2]:
ans = nums1[p1]
p1 += 1
else:
ans = nums2[p2]
p2 += 1
elif p2 == n:
ans = nums1[p1]
p1 += 1
else:
ans = nums2[p2]
p2 += 1
return ans
if (m + n) % 2 == 0:
for _ in range((m + n) // 2 - 1):
_ = get_min()
return (get_min() + get_min()) / 2
else:
for _ in range((m + n) // 2):
_ = get_min()
return get_min()
## Example usage:# sol = Solution()
# print(sol.findMedianSortedArrays([1, 3], [2])) # Output: 2.0
# print(sol.findMedianSortedArrays([1, 2], [3, 4])) # Output: 2.5
# time complexity: O(m + n) space complexity: O(1)