[leetcode]Median of Two Sorted Arrays

题目:There are two sorted arrays A and B 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)).

链接:https://oj.leetcode.com/problems/median-of-two-sorted-arrays/

描述:对数时间复杂度寻找两个数组中的中位数

思路:实现查找两个有序数组的第k个元素的算法,需要注意边界问题:1.保证每次截取的子数组长度不会超过长度较小的数组 2.处理当一个数组长度为0或长度为1的情况 3.求中位数要注意如果总长度为偶数,需要求中间两个数的平均数

solution by python:

class Solution:
    # @return a float
    def findMedianSortedArrays(self, A, B):
        n = len(A) + len(B)
        if n&0x1:
            return self.findkth(A, B, n/2+1)
        else:
            return (float(self.findkth(A,B,n/2)) + self.findkth(A,B,n/2+1))/2
    def findkth(self, A,B,k):
        if len(A) > len(B):
            return self.findkth(B, A, k)
        if len(A) == 0:
            return B[k-1]
        if k == 1:
            return min(A[0], B[0])
        idx = min(k/2, len(A))
        if A[idx-1] < B[idx-1]:
            return self.findkth(A[idx:], B, k-idx)
        else:
            return self.findkth(A, B[idx:], k-idx)

solution by c++:

class Solution {
public:
    int findKth(int *A, int *B, int m, int n, int k){
        if( m > n)
            return findKth(B,A,n,m,k);
        if(m == 0) return B[k-1];
        if(k == 1) return A[0]<B[0]? A[0]:B[0];
        int pa = min(k/2, m);
        int pb = k - pa;
        if(A[pa-1] == B[pb-1]) return A[pa-1];
        if(A[pa-1] < B[pb-1])
            return findKth(A+pa, B, m-pa, n, k-pa);
        return findKth(A, B+pb, m, n-pb, k-pb);
    }
    double findMedianSortedArrays(int A[], int m, int B[], int n) {
        int total = m+n;
        if(total & 1){
            return findKth(A,B,m,n,total/2+1);
        }
        return (double(findKth(A,B,m,n,total/2)+findKth(A,B,m,n,total/2+1)))/2;
    }
};



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值