首页 > 其他 > 详细

Median of Two Sorted Arrays

时间:2015-10-29 13:39:24      阅读:204      评论:0      收藏:0      [点我收藏+]

问题链接:https://leetcode.com/problems/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)).

c++ 40ms

class Solution { 
public: 
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { 
        int mid = (nums1.size() + nums2.size() - 1)/2; 
        int flag = (nums1.size() + nums2.size())%2; 
        int index1 = 0, index2 = 0, temp = 0; 
        double medina = 0; 
        while ((index1 < nums1.size() || index2 < nums2.size()) && (index1 + index2) <= mid + 1) 
        { 
            if (index1 == nums1.size()) 
            { 
                temp = nums2[index2]; 
                ++index2; 
            } 
            else if (index2 == nums2.size()) 
            { 
                temp = nums1[index1]; 
                ++index1; 
            } 
            else if (nums1[index1] < nums2[index2]) 
            { 
                temp = nums1[index1]; 
                ++index1; 
            } 
            else 
            { 
                temp = nums2[index2]; 
                ++index2; 
            } 
 
            if ((index1 + index2 - 1) == mid) 
            { 
                medina += temp; 
            } 
            if (!flag&&(index1 + index2 - 1) == mid + 1) 
            { 
                medina += temp; 
            } 
        } 
        if (!flag) 
            medina /= 2; 
        return medina; 
    } 
};


Median of Two Sorted Arrays

原文:http://my.oschina.net/u/2313065/blog/523448

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!