We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent eb51c41 commit 5cc666dCopy full SHA for 5cc666d
1 file changed
leetcode/4. Median of Two Sorted Arrays
@@ -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
38
+ elif a[i] <= b[j]:
39
40
41
+ elif a[i] > b[j]:
42
43
44
+ k-=1
45
46
+ if flag:
47
+ return a[i-1]
48
49
+ return b[j-1]
0 commit comments