首页 > 解决方案 > 两个排序数组的中位数超过时间限制的问题

问题描述

在超过时间限制的情况下解决 LeetCode 上的测验时遇到了麻烦。这两天我一直在解决这个问题,但我仍然不明白为什么它不能通过。

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int leng1 = nums1.size();
        int leng2 = nums2.size();
        int combinedleng = leng1 + leng2;
        int head = 0, tail = leng1;
        int cut1, cut2;
        bool found = false;
        
            if(leng1 > leng2 && leng2 != leng1){return findMedianSortedArrays(nums2, nums1);}
        
        while(head <= tail && !found) {
            cut1 = (head + tail)/2;
            cut2 = (combinedleng +1)/2 - cut1;
                double L1 = (cut1 == 0) ? INT_MIN : nums1[cut1-1];
                double L2 = (cut2 == 0) ? INT_MIN : nums2[cut2-1];
                double R1 = (cut1 == leng1) ? INT_MAX : nums1[cut1];
                double R2 = (cut2 == leng2) ? INT_MAX : nums2[cut2];
                    if(L1 > R2){head = cut1 -1;}
                    else if(L2 > R1){head = cut1 +1;}
                    else {
                            if(combinedleng %2 ==0){return (max(L1, L2) + min(R1, R2))/2;}
                            else{return max(L1,L2);}
                    }
        }
     return -1;
    }
};

当测试用例 [3,4][1,2] 时,代码结果将是 'nums1' 必须是非递减的。

标签: c++data-structures

解决方案


推荐阅读