[Py] Median of Two Sorted Arrays

Median of Two Sorted Arrays (leetcode.com)

2085 / 2085 test cases passed.
Status: Accepted
Runtime: 120 ms (19.98%)
Memory Usage: 14.1 MB

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        n1n = len(nums1)
        n2n = len(nums2)
        if n1n == 0: # if num1 is empty
            if (n2n % 2) == 1: # Odd 
                return nums2[n2n//2]
            else:
                return (nums2[n2n//2]+nums2[(n2n//2)-1])/2
        elif n2n == 0 :# if num2 is empty
            if (n1n % 2) == 1: # Odd 
                return nums1[n1n//2]
            else:
                return (nums1[n1n//2]+nums1[(n1n//2)-1])/2
        else: # both are not empty
            Arr=[]
            n1i=0 #cursor1 for num1
            n2i=0 #cursor2 for num2
            while(n1i<n1n or n2i<n2n):
                if n1i >= n1n and n2i<n2n: #num1 is all added to new array
                    Arr.append(nums2[n2i])
                    n2i+=1
                    continue
                elif n1i<n1n and n2i>=n2n: #num2 is all added to new array
                    Arr.append(nums1[n1i])
                    n1i+=1
                    continue
                else: # both nums1 and nums2 have elements
                    if nums1[n1i] <= nums2[n2i]:
                        Arr.append(nums1[n1i])
                        n1i+=1
                        continue
                    else:
                        Arr.append(nums2[n2i])
                        n2i+=1
                        continue
            # After all elements added to new array, find the median.
            An = len(Arr)
            if (An%2)==1: #Odd
                return Arr[An//2]
            else:
                return (Arr[An//2]+Arr[(An//2)-1])/2

請多多指教!

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料