Skip to content

Commit 5cc666d

Browse files
Create 4. Median of Two Sorted Arrays
1 parent eb51c41 commit 5cc666d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
'''
2+
There are two sorted arrays nums1 and nums2 of size m and n respectively.
3+
4+
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
5+
6+
Example 1:
7+
nums1 = [1, 3]
8+
nums2 = [2]
9+
10+
The median is 2.0
11+
Example 2:
12+
nums1 = [1, 2]
13+
nums2 = [3, 4]
14+
15+
The median is (2 + 3)/2 = 2.5
16+
'''
17+
class Solution(object):
18+
def findMedianSortedArrays(self, a, b):
19+
n = len(a)+len(b)
20+
if n&1:
21+
return self.kthSmallest(a,b,n//2+1)
22+
else:
23+
return (self.kthSmallest(a,b,n//2+1) + self.kthSmallest(a,b,n//2))/2.0
24+
25+
def kthSmallest(self,a,b,k):
26+
if len(a)+len(b) < k:
27+
return None
28+
i=0
29+
j=0
30+
flag = True
31+
while k>0:
32+
if i >= len(a):
33+
j+=1
34+
flag = False
35+
elif j >= len(b):
36+
i+=1
37+
flag = True
38+
elif a[i] <= b[j]:
39+
i+=1
40+
flag = True
41+
elif a[i] > b[j]:
42+
j+=1
43+
flag = False
44+
k-=1
45+
46+
if flag:
47+
return a[i-1]
48+
else:
49+
return b[j-1]

0 commit comments

Comments
 (0)