forked from taizilongxu/interview_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmedianoftwosortedarray.py
More file actions
69 lines (61 loc) · 1.6 KB
/
medianoftwosortedarray.py
File metadata and controls
69 lines (61 loc) · 1.6 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
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
import sys
import random
def findMedian1(v1, v2):
v = []
i = 0
j = 0
vlen = len(v1)+len(v2)
while i < len(v1) and j < len(v2):
if v1[i] < v2[j]:
v.append(v1[i])
i += 1
else:
v.append(v2[j])
j += 1
v += v1[i:]
v += v2[j:]
if vlen % 2 == 1 or vlen == 1:
return v[vlen//2]
else:
return (v[vlen//2]+v[vlen//2 -1])/2
def findKth(v1, v2, k):
len1, len2 = len(v1), len(v2)
if len1 == 0:
return v2[k-1]
if len2 == 0:
return v1[k-1]
if k == 1:
return min(v1[0], v2[0])
key1, key2 = sys.maxsize, sys.maxsize
if k//2 - 1 < len1:
key1 = v1[k//2 - 1]
if k//2 - 1 < len2:
key2 = v2[k//2 - 1]
if key1 < key2:
return findKth(v1[k//2:], v2, k - k//2)
else:
return findKth(v1, v2[k//2:], k - k//2)
def findMedian2(v1, v2):
len1, len2 = len(v1), len(v2)
if (len1+len2)% 2 == 1:
return findKth(v1, v2, (len1+len2)//2+1)
else:
return (findKth(v1, v2, (len1+len2)//2) + findKth(v1, v2, (len1+len2)//2+1))/2
def stressTesting():
while True:
a = random.randint(50, 100)
b = random.randint(2, 50)
L1, L2 = [], []
for i in range(a):
L1.append(random.randrange(1, a))
for i in range(b):
L2.append(random.randrange(1, b))
L1.sort()
L2.sort()
print(L1)
print(L2)
print(findMedian1(L1, L2))
print(findMedian2(L1, L2))
if findMedian1(L1, L2) != findMedian2(L1, L2):
break
stressTesting()