LintCode 65: Median of two Sorted Arrays (经典题!!!)

本文介绍了一种使用二分查找法寻找两个已排序数组中第K小元素的方法,该方法通过比较两个数组的中间元素来缩小搜索范围,最终找到目标元素,时间复杂度为O(log(m+n))。

这题解法很多。

解法1: 二分法。
找两个排序数组中第K小的数。

  1. If startA exceeds A.size(), then the Kth smallest elements should be B[startB + K -1];
    If startA exceeds A.size(), then the Kth smallest elements should be B[startB + K -1];

  2. if K == 1, then return the min of A[startA] and B[startB]

  3. if startA + K / 2 is still within arrayA, and
    startB + K / 2 is still within arrayB, then compare halfKOfA and halfKOfB:

if halfKOfA > halfKOfB, then the Kth smallest number should be in
A[startA…startA+K/2] and B[startB+K/2…startB+K]

if halfKOfA < halfKOfB, then the Kth smallest number should be in
A[startA+K/2…startA+K] and B[startB…startB+K/2]

Time complexity O(log(m+n)).

class Solution {
public:
    /*
     * @param A: An integer array
     * @param B: An integer array
     * @return: a double whose format is *.5 or *.0
     */
    double findMedianSortedArrays(vector<int> &A, vector<int> &B) {
        int totalLen = A.size() + B.size();
        
        if (totalLen & 0x1) {
            return helper(A, 0, B, 0, totalLen / 2 + 1);
        } else {
            return helper(A, 0, B, 0, totalLen / 2) / 2.0 + helper(A, 0, B, 0, totalLen / 2 + 1) / 2.0;
        }
        
    }
    
private:
    int helper(vector<int> &A, int startA, vector<int> &B, int startB, int K) {
        if (startA >= A.size()) {
            return B[startB + K - 1];
        }
        
        if (startB >= B.size()) {
            return A[startA + K - 1];
        }
        
        if (K == 1) {
            return min(A[startA], B[startB]);
        }
        
        int halfKofA = 0, halfKofB = 0; 
    
        if ((startA + K / 2) > A.size()) {
            halfKofA = INT_MAX;
        } else {
            halfKofA = A[startA + K / 2 - 1];
        }
        
        if ((startB + K / 2) > B.size()) {
            halfKofB = INT_MAX;
        } else {
            halfKofB = B[startB + K / 2 - 1];
        }
        
        if (halfKofA > halfKofB) {
            // should be in the other k/2 of B
            return helper(A, startA, B, startB + K / 2, K - K / 2);
            //return helper(A, startA, B, startB + K / 2, K / 2);
        } else {
            // should be in the other k/2 of a
            return helper(A, startA + K / 2, B, startB, K - K / 2 );
            //return helper(A, startA + K / 2, B, startB, K / 2 );
        }
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值