LeetCode:两个排序数组的中位数 C++/Python

 

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2 

请找出这两个有序数组的中位数。要求算法的时间复杂度为 O(log (m+n)) 。

示例 1:

nums1 = [1, 3]
nums2 = [2]

中位数是 2.0

示例 2:

nums1 = [1, 2]
nums2 = [3, 4]

中位数是 (2 + 3)/2 = 2.5

C++

有时间复杂度要求,用的二分法。

没有的话直接存入数组,取中间值,时间复杂度O(m+n)。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size(), n = nums2.size();
        if(n < m)
        {
            vector<int> temp = nums1;
            nums1 = nums2;
            nums2 = temp;
            int t = m;
            m = n;
            n = t;
        }
        int min = 0, max = m;
        while(min <= max)
        {
            int i = (min + max) / 2;
            int j = (m + n +1) / 2 - i;
            if (i < max && nums2[j-1] > nums1[i])
            {
                min = min + 1;
            }
            else if (i > min && nums1[i-1] > nums2[j])
            {
                max = max - 1; 
            }
            else
            {
                int l, r;
                if(i == 0) l = nums2[j-1];
                else if(j == 0) l = nums1[i-1];
                else l = (nums1[i-1] > nums2[j-1])?nums1[i-1]:nums2[j-1];
                
                if ((m + n) % 2 == 1 ) { return l; }
                
                if(i == m) r = nums2[j];
                else if(j == n) r = nums1[i];
                else r = (nums1[i] < nums2[j])?nums1[i]:nums2[j];
                
                return (l + r)/2.0;
            }
        }
    }
};

 

Python

class Solution:
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        l1 = nums1 + nums2
        l1.sort()
        if len(l1) % 2 == 0:
            a = len(l1) // 2
            return (l1[a-1] + l1[a]) / 2
        else :
            a = len(l1) / 2
            return l1[math.floor(a)]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值