zoukankan      html  css  js  c++  java
  • LeetCode "Median of Two Sorted Arrays"

    1A! We get median of each array and compare them, then we know which half should be disguarded and how many should be disguarded.

    class Solution {
    public:
        double findMidArr(int A[], int s, int e, int &chopLen)
        {
            int len = e - s + 1;
            chopLen = (s + e) / 2 - s;
            if (len % 2)    return A[(s + e) / 2];
            else            return (A[(s + e) / 2] + A[(s + e) / 2 + 1]) / 2.0;
        }
        double findMidMinor(int sm[], int cntSm, int lg[], int cntLg)
        {
            vector<int> v;
            v.assign(lg, lg + cntLg);
            
            v.insert(v.end(), sm, sm + cntSm);
            std::sort(v.begin(), v.end());
    
            size_t len = v.size();
            if (len % 2)    return v[len / 2];
            else            return (v[len / 2] + v[len / 2 - 1]) / 2.0;
        }
        double findMid(int A[], int sa, int ea, int B[], int sb, int eb)
        {
            int lenA = ea - sa + 1;
            int lenB = eb - sb + 1;
    
            //    Base cases
            if (lenA <= 2)    return findMidMinor(A + sa, lenA, B + sb, lenB);
            if (lenB <= 2)    return findMidMinor(B + sb, lenB, A + sa, lenA);
    
            //    Chop
            int chopLenA, chopLenB;
            double midA = findMidArr(A, sa, ea, chopLenA);
            double midB = findMidArr(B, sb, eb, chopLenB);
            int chopLen = std::min(chopLenA, chopLenB);
    
            if (midA == midB) return midA;
            else if (midA < midB)    return findMid(A, sa + chopLen, ea, B, sb, eb - chopLen);
            else if (midB < midA)    return findMid(A, sa, ea - chopLen, B, sb + chopLen, eb);
        }
        double findMedianSortedArrays(int A[], int m, int B[], int n) {
            return findMid(A, 0, m - 1, B, 0, n - 1);
        }
    };
  • 相关阅读:
    S02_CH15_ AXI_OLED 实验
    S02_CH14_ EMIO_OLED 实验
    S02_CH13_ AXI_PWM 实验
    S02_CH12_ AXI_Lite 总线详解
    【第二季】CH11_ ZYNQ软硬调试高级技巧
    bzoj3028 食物
    Hdu3579 Hello Kiki
    bzoj4872 [Shoi2017]分手是祝愿
    bzoj4873 [Shoi2017]寿司餐厅
    省选模拟赛 LYK loves rabbits(rabbits)
  • 原文地址:https://www.cnblogs.com/tonix/p/3926873.html
Copyright © 2011-2022 走看看