leetcode刷题日常-第4题

Problem: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)).

You may assume nums1 and nums2 cannot be both empty.

solution:

 double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        vector<int> tmp;
        vector<int> tmp_long;
        vector<int> tmp_short;
        if (nums1.size() == 0)
            tmp = nums2;
        if (nums2.size() == 0)
            tmp = nums1;
        if (tmp.size() % 2 == 0 && tmp.size() != 0)
            return (double)(tmp[tmp.size() / 2] + tmp[tmp.size() / 2 - 1]) / 2;
        if (tmp.size() % 2 != 0)
            return tmp[tmp.size() / 2];
        if (nums1.size() < nums2.size())
        {
            tmp_long = nums2;
            tmp_short = nums1;
        }
        else
        {
            tmp_long = nums1;
            tmp_short = nums2;
        }
        int count = 0;
        int temp = nums1[0] < nums2[0] ? nums1[0] : nums2[0];
        int j_index = 0;
        int median_number = (nums1.size() + nums2.size()) / 2 + 1;

        for (int i = 0; i < tmp_long.size();)
        {
            if (tmp_long[i] <= temp)
            {
                tmp.push_back(tmp_long[i]);
                count++;
                i++;
                if (count == median_number)
                break;
                if (i < tmp_long.size())
                    continue;

            }
            else
                temp = tmp_long[i];

            for (int j = j_index; j < tmp_short.size();)
            {
                if (tmp_short[j] <= temp)
                {
                    tmp.push_back(tmp_short[j]);
                    count++;
                    j_index++;
                    j++;
                    if (count == median_number)
                         break;
                }
                else
                {
                    temp = tmp_short[j];
                    if(i !=tmp_long.size())
                        break;
                }

            }
            if (count == median_number)
                break;
        }
        if ((nums1.size() + nums2.size()) % 2 == 0)
            return (double)(tmp[tmp.size() - 1] + tmp[tmp.size() - 2]) / 2;
        else
            return tmp[tmp.size() - 1];
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值