博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode "Median of Two Sorted Arrays"
阅读量:4628 次
发布时间:2019-06-09

本文共 1683 字,大约阅读时间需要 5 分钟。

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
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); }};

转载于:https://www.cnblogs.com/tonix/p/3926873.html

你可能感兴趣的文章
PHP+nginx 线上服务研究(一)
查看>>
Python学习教程:超干货—Python3内置模块之json编解码方法小结
查看>>
谷歌浏览器的一个新特点—关于获取iframe的parent对象
查看>>
iOS开发Swift篇—(二)变量和常量
查看>>
Windows底层开发前期学习准备工作
查看>>
【C语言及程序设计】项目1-39-3:反序数
查看>>
算法——查找常用字符
查看>>
ANDORID~支持的设备
查看>>
国内外 Java Script 经典封装
查看>>
[vs2005]关于预编绎网站的问题[已预编译此应用程序的错误]
查看>>
find_in_set
查看>>
[HEOI2015]定价
查看>>
题解 洛谷P3203/BZOJ2002【[HNOI2010]弹飞绵羊】
查看>>
机器学习基石的泛化理论及VC维部分整理
查看>>
《php源码学习研究》 第一天
查看>>
C++虚函数和纯虚函数的异同
查看>>
checkbox操作
查看>>
Spring概念
查看>>
VS2017 添加引用报错问题
查看>>
LeetCode 147. Insertion Sort List
查看>>