LeetCode —— Median of Two Sorted Arrays

来源:互联网 发布:国产pdf编辑软件 编辑:程序博客网 时间:2024/05/29 19:03

链接:http://leetcode.com/onlinejudge#question_4

原题:There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

思路:取两个数组的中间数比较,然后各自去除相同的长度,这样一来又是原来的问题,仍然找中间的数。

这道题目投机了一下,当数组个数有一个小于6时,我就直接归并了一下,搞定。可以少很多if,else。


代码:

class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int aL = 0;        int aR = m - 1;        int bL = 0;        int bR = n - 1;        while (true) {            int aLen = aR - aL + 1;            int bLen = bR - bL + 1;            if (aLen <= 5 || bLen <= 5)                return getMedian(A, aL, aR, B, bL, bR);                        int aMid = (aL + aR) / 2;            int bMid = (bL + bR) / 2;            if (A[aMid] <= B[bMid]) {                int minDel = min(aMid - aL - 1, bR - bMid - 1);                aL += minDel;                bR -= minDel;            } else {                int minDel = min(bMid - bL - 1, aR - aMid - 1);                bL += minDel;                aR -= minDel;            }        }    }private:    double getMedian(int A[], int aL, int aR, int B[], int bL, int bR) {        int i = aL;        int j = bL;        vector<int> vec;        while (i<=aR && j<=bR) {            if (A[i] <= B[j])                vec.push_back(A[i++]);            else                vec.push_back(B[j++]);        }                while (i<=aR)            vec.push_back(A[i++]);                while (j<=bR)            vec.push_back(B[j++]);                    if (vec.size() == 0)            return 0;                if (vec.size() % 2 == 1)            return vec[vec.size()/2];        else            return (vec[vec.size()/2-1] + vec[vec.size()/2]) / 2.0;    }};


原创粉丝点击