Skip to content

Commit

Permalink
Update Median of Two Sorted Arrays.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb authored Aug 28, 2022
1 parent 608c1d0 commit b4a0f2c
Showing 1 changed file with 37 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,42 @@
# https://leetcode.com/problems/median-of-two-sorted-arrays/

# -------------------- Method 1 --------- NOT Optimised O(N) Time----------------
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
n1 = len(nums1); n2 = len(nums2)
mid = (n1 + n2) // 2
i = 0; j = 0
val, preVal = 0, 0

for k in range(mid+1):
if i < n1 and j < n2:
if nums1[i] <= nums2[j]:
val = nums1[i]
i += 1
else:
val = nums2[j]
j += 1
elif i < n1:
val = nums1[i]
i += 1
else:
val = nums2[j]
j += 1

if k == mid - 1:
preVal = val

if (n1+n2) % 2 == 0:
return (val + preVal) / 2
return float(val)

# Timw: O(N)
# Space: O(1)



# -------------------- Method 2 --------- Optimised O(log(N)) Time----------------

# https://www.youtube.com/watch?v=NTop3VTjmxk
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
Expand Down

0 comments on commit b4a0f2c

Please sign in to comment.