【LeetCode】4. Median of Two Sorted Arrays(Python)

Problem

有两个排序的数组nums1和nums2分别为m和n。
找到两个排序数组的中位数。总运行时间复杂度应为O(log(m + n))。
您可以假设nums1和nums2 不能都为空。

例1:
nums1 = [1,3]
nums2 = [2]
中位数是2.0

例2:
nums1 = [1,2]
nums2 = [3,4]
中位数为(2 + 3)/ 2 = 2.5

Algorithmic thinking

方法1:递归方法
要解决这个问题,我们需要了解“中位数有什么用”。在统计中,中位数用于:
将一组分成两个相等长度的子集,一个子集总是大于另一个子集。
如果我们理解使用中位数来划分,我们非常接近答案。

Python code

solution 1

class Solution:
    def findMedianSortedArrays(self, A, B):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        # n>=m 
        m, n = len(A),len(B)
        if n<m:
            A, B, m, n = B, A, n, m
        
        imin, imax, halfLen = 0, m, (m+n+1)/2
        while(imin <= imax):
            i = int((imin+imax)/2)
            j = int(halfLen)-i
            if i > 0 and A[i-1] > B[j]:
                imax = i - 1
            elif i < m and A[i] < B[j-1]:
                imin = i + 1
            else:
                # i is perfect
                if i==0:
                    maxLeft = B[j-1]
                elif j==0:
                    maxLeft = A[i-1]
                else:
                    maxLeft = max(A[i-1], B[j-1])
                
                if (m+n) % 2 == 1:
                    return maxLeft
                else:
                    if i==m:
                        minRight = B[j]
                    elif j==n:
                        minRight = A[i]
                    else:
                        minRight = min(B[j],A[i])
                return (maxLeft+minRight)/2

solution 2

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
4. Median of Two Sorted Arrays
Hard

There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.

Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0

Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
"""


class Solution:
    def findMedianSortedArrays(self, x, y):
        z = len(x) + len(y)
        return self.findKth(x, y, z//2) if z % 2 == 1 \
            else (self.findKth(x, y, z//2-1)+self.findKth(x, y, z//2))/2.0

    def findKth(self, list1, list2, k):
        if len(list1) > len(list2):
            list1, list2 = list2, list1
        if not list1:
            return list2[k]
        if k == len(list1) + len(list2) - 1:
            return max(list1[-1], list2[-1])
        i = len(list1) // 2
        j = k - i
        if list1[i] > list2[j]:
            # Here it's O(1) to get list1[:i] and list2[j:].
            return self.findKth(list1[:i], list2[j:], i)
        else:
            return self.findKth(list1[i:], list2[:j], j)


if __name__ == '__main__':
    nums1 = (1, 2, 3, 4)
    nums2 = (3, 4)
    result = Solution().findMedianSortedArrays(nums1, nums2)
    print(result)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值