第四题

作者: cde99bf0b5b1 | 来源:发表于2017-09-06 12:23 被阅读0次
#include <algorithm>
using namespace std;
class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        double res;
        if(nums1.size()==0&&nums2.size()==0)
            return 0;
        if(nums1.size() == 0){
            int size = nums2.size();
            return double((nums2[(size-1)/2] + nums2[size/2]))/2;
        }
        if(nums2.size() == 0){
            int size = nums1.size();
            return double((nums1[(size-1)/2] + nums1[size/2]))/2;
        }
        int i1 = -1, i2 = -1;
        int next = 0, pre = 0;
        int mid = (nums1.size() + nums2.size())/2;
        for(int i = 0; i <= mid; i++){
            if(i1+1 >= nums1.size()){
                i2++;
            }
            else if(i2+1 >= nums2.size()){
                i1++;
            }
            else if(nums1[i1+1] <= nums2[i2+1]){
                i1++;
            }
            else
                i2++;
            if(i == mid-1){
                if(i1 == -1){
                    pre = nums2[i2];
                }
                else if(i2 == -1){
                    pre = nums1[i1];
                }
                else{
                    pre = max(nums1[i1],nums2[i2]);
                }
            }
            if(i == mid){
                if(i1 == -1){
                    next = nums2[i2];
                }
                else if(i2 == -1){
                    next = nums1[i1];
                }
                else{
                    next = max(nums1[i1],nums2[i2]);
                }
            }
        }
        if((nums1.size() + nums2.size())%2 == 0){
            res = double((next + pre))/2;
        }
        else{
            res = next;
        }
        return res;
    }
};

相关文章

网友评论

      本文标题:第四题

      本文链接:https://www.haomeiwen.com/subject/yxgmjxtx.html