编程语言
首页 > 编程语言> > python 寻找两个正序数组的中位数(leetcode)

python 寻找两个正序数组的中位数(leetcode)

作者:互联网

给定两个大小分别为m和n 的正序(从小到大)数组nums1 和nums2.请你找出并返回这两个正序数组的中位数。
算法是时间复杂度应该为o(log(m*n))

class Solution1:
    def findMedianSortedArrays(self, nums1, nums2) -> float:
        nums1.extend(nums2)
        length = len(nums1)
        nums1.sort()
        return nums1[length//2] if length ^ 1 < length else (nums1[length//2] + nums1[length//2-1])/2
class Solution:
    def findMedianSortedArrays(self, nums1, nums2) -> float:
        l1 = len(nums1)
        l2 = len(nums2)
        stack = []
        index2 = 0
        index1 = 0
        while index1 < l1 and index2 < l2:
            while index1 < l1 and nums1[index1] <= nums2[index2]:
                stack.append(nums1[index1])
                index1 += 1
            if index1 >= l1:
                break
            while index2 < l2 and nums1[index1] > nums2[index2] :
                stack.append(nums2[index2])
                index2 += 1
        if index1 >= l1:
            stack = stack + nums2[index2:]
        else:
            stack = stack + nums1[index1:]
        length=len(stack)
        return stack[length//2] if length ^ 1 < length else (stack[length//2] + stack[length//2-1])/2

标签:正序,python,nums1,stack,length,index2,index1,leetcode,nums2
来源: https://blog.csdn.net/weixin_44224529/article/details/121437274