-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedian_of_two_sorted_arrays.py
75 lines (57 loc) · 1.83 KB
/
median_of_two_sorted_arrays.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# https://leetcode.com/problems/median-of-two-sorted-arrays/
import math
def findMedianSortedArrays(nums1: list, nums2: list) -> float:
n = len(nums1)
m = len(nums2)
x = math.floor(m+n)/2
isPair = (m+n) % 2 == 0
i = 0
j = 0
current = ""
prev = ""
while True:
# print(f" i = {i} , j ={j}")
if not isPair and i+j >= x: # caso final array long impar
print(f"Caso impar i = {i} , j ={j}")
if current == "i":
return nums1[i-1]
elif current == "j":
return nums2[j-1]
elif isPair and i+j >= x+1: # caso final array long par
print(f"Caso par i = {i} , j ={j}")
if current == "i" and prev == "i":
return (nums1[i-1]+nums1[i-2])/2
if current == "i" and prev == "j":
return (nums1[i-1]+nums2[j-1])/2
if current == "j" and prev == "i":
return (nums2[j-1]+nums1[i-1])/2
if current == "j" and prev == "j":
return (nums2[j-1]+nums2[j-2])/2
if len(nums1) == 0:
j += 1
prev = current
current = "j"
elif len(nums2) == 0:
i += 1
prev = current
current = "i"
elif i == n:
j += 1
prev = current
current = "j"
elif j == m:
i += 1
prev = current
current = "i"
elif nums1[i] < nums2[j]:
i += 1
prev = current
current = "i"
elif nums2[j] < nums1[i]:
j += 1
prev = current
current = "j"
elif nums1[i] == nums2[j]:
i += 1
prev = current
current = "i"