Leetcode--Median of Two Sorted Arrays

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode--Median of Two Sorted Arrays相关的知识,希望对你有一定的参考价值。

这道题感觉没什么讲的,需要注意的就是,num1,num2的长度并不相等,会有可能num2还没到尽头,num1就到尽头了

    static double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) {
        auto length = nums1.size() + nums2.size();
        int x = 0, y = 0, even = 0, i = 0;
        double results[2] = {0, 0};
        double result = 0;
        if (length % 2 == 0) {
            length = (length / 2)+1;
            even = 1;
        } else length = (length + 1) / 2;
        while (length != 0 && x < nums1.size() && y < nums2.size()) {
            if(nums1[x]==nums2[y]){
                results[i]=nums1[x];
                ++x;
            }
            else if (nums1[x] > nums2[y]) {
                results[i] = nums2[y];
                ++y;
            } else {
                results[i] = nums1[x];
                ++x;
            }
            i = ++i % 2;
            --length;
        }
        if (length != 0) {
            if (x < nums1.size())
                while (length != 0) {
                    results[i] = nums1[x];
                    i = ++i % 2;
                    ++x;
                    --length;
                }
            else {
                while (length != 0) {
                    results[i] = nums2[y];
                    i = ++i % 2;
                    ++y;
                    --length;
                }
            }
        }
        if (even)
            result = (results[0] + results[1]) / 2;
        else {
            result = results[0] > results[1] ? results[0] : results[1];
        }
        return  result;
    }

另在网上看到了一种优化算法,不过看了很久还是不怎么懂,地址在这里:

http://blog.csdn.net/linhuanmars/article/details/19905515

以上是关于Leetcode--Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Median of Two Sorted Arrays

LeetCode--median-of-two-sorted-arrays

LeetCode: Median of Two Sorted Arrays

LeetCode4 :median of two sorted arrays---求两个有序数组的中位数

LeetCode - Median of Two Sorted Arrays

LeetCode:Median of Two Sorted Arrays