Leetcode_4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 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)).

Example 1:

nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

解析:求数组的中位数 。这道题好像剑指offer上有。
使用大根堆和小根堆的性质,左边为大根堆,右边为小根堆,那么两个堆的序列合并起来数据还是有序的,当个数为奇数的时候将值压进大根堆,为偶数的时候将其压入小根堆。但是要注意的是在将其压入堆之前得放进另外一个堆,然后取堆顶,因为比如大根堆为3 5 小根堆为6 7 如果加入8 那么直接加入大根堆就错了,得加入小根堆,然后取堆顶6 那么加入大根堆后左边为3 5 6 右边为7 8 正确。

代码:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
    {   
        priority_queue<int>q1;//大根堆
        priority_queue<int,vector<int>,greater<int> >q2;//小根堆
        int cnt = 0;
        double ans;
        vector<int>vec;
        for(int i=0;i<nums1.size();i++)  vec.push_back(nums1[i]);
        for(int i=0;i<nums2.size();i++)  vec.push_back(nums2[i]);
        for(int i=0;i<vec.size();i++) 
        {
            ++cnt;
            if(cnt%2)
            {
                q2.push(vec[i]);
                int top_val = q2.top();
                q2.pop();
                q1.push(top_val);
            }
            else
            {
                q1.push(vec[i]);
                int top_val = q1.top();
                q1.pop();
                q2.push(top_val);
            }
        }
        int size = vec.size();
        if(size%2)  ans = q1.top()*1.0;
        else  ans = (q1.top()+q2.top())*1.0/2;
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/u014303647/article/details/80303382