leetcode 4 - binary search

注意:

1)需要保证nums1 的长度比 nums2 的长度小;(否则vector指针会越界)

2)  当分割线(partition)在首或尾时,用INT_MIN 和 INT_MAX 代替。

思路:

 

class Solution {
public:
    double static findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

        int x = nums1.size();
        int y = nums2.size();
        
        if(x>y)
            return findMedianSortedArrays(nums2, nums1);
        
        int l = x + y;
        int length = (x + y + 1) / 2;
        double median = 0;
        //vector x 中:
        int start = 0;
        int end = x;

        while (start <= end) {
            //cout << start << endl << end << endl;
            int p_x = (start + end) / 2;
            int p_y = length - p_x;

            //if p_x is 0 it means nothing is there on left side, use -INF for maxLeftX
            //if p_x is length of input then there is nothing on right side, use +INF for minRightX
            double maxLeftX = (p_x == 0) ? INT_MIN : nums1[p_x - 1];
            double minRightX = (p_x == x) ? INT_MAX : nums1[p_x];

            double maxLeftY = (p_y == 0) ? INT_MIN : nums2[p_y - 1];
            double minRightY = (p_y == y) ? INT_MAX : nums2[p_y];

            if (maxLeftX <= minRightY && maxLeftY <= minRightX)
            {
                if (l % 2 == 0)
                    //长度为偶数
                    {
                        median = (max(maxLeftX, maxLeftY)+ min(minRightX, minRightY)) / 2.0;
                        //cout << max(maxLeftX, maxLeftY) << endl << min(minRightX, minRightY) << endl;
                    }
                else
                    median = max(maxLeftX, maxLeftY);
                return median;
            }
            else if (maxLeftX > minRightY)
                end = p_x - 1;       //nums1的分割线左移
            else if (maxLeftY > minRightX)
                start = p_x + 1;   //nums1的分割线右移
        }
        return -1;
    }
};

 

posted @ 2019-03-17 14:43  爱学英语的程序媛  阅读(140)  评论(0编辑  收藏  举报