• leetcode 4


    注意:

    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;
        }
    };
  • 相关阅读:
    Java数据类型转换
    github的入门使用
    移动端的头部标签和meta
    gulp&gulp-less
    前端工程筹建NodeJs+gulp+bower
    jQuery 遍历
    JavaScript for...in 语句
    console.log在线调试
    sessionStorage html5客户端本地存储之sessionStorage及storage事件
    一个页面从输入url到加载完成的过程都发生了什么,请详细说明
  • 原文地址:https://www.cnblogs.com/Bella2017/p/10546961.html
Copyright © 2020-2023  润新知