码迷,mamicode.com
首页 > 其他好文 > 详细

4. Median of Two Sorted Arrays

时间:2016-06-23 22:22:31      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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

==============

找出两个数组的中位数,

中位数的定义是明确的:按序排好的数组,array.size=n是奇数的话,第(n+1)/2个数字;否则就是第n/2和第(n+1)/2的平均数。

==========思路:

划分思路,

第一步:按照归并思路找到两个数组中的第k大

第二步:按照计算中位数的方法,返回中位数。

=========

code实现,

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int lengtha = nums1.size();
        int lengthb = nums2.size();
        int total = lengtha+lengthb;
        if(total & 0x1){
            return find_kth(nums1,nums2,total/2+1);
        }else{
            return (find_kth(nums1,nums2,total/2)+
                    find_kth(nums1,nums2,total/2+1))/2.0;
        }
    }
private:
    int find_kth(vector<int> &A,vector<int> &B,int k){
        std::vector<int>::const_iterator p1 = A.begin();
        std::vector<int>::const_iterator p2 = B.begin();
        int m = 0;
        while(p1!=A.end() && p2!=B.end()){
            if(*p1<=*p2 && m==(k-1)){
                return *p1;
            }else if(*p1>*p2 && m==(k-1)){
                return *p2;
            }
            if(*p1<=*p2)
                p1++;
            else
                p2++;
            m++;
        }//while
        while(p1!=A.end()){
            if(m==(k-1)){
                return *p1;
            }
            p1++;
            m++;
        }
        while(p2!=B.end()){
            if(m==(k-1)){
                return *p2;
            }
            p2++;
            m++;
        }
        return -1;
    }
};

 

4. Median of Two Sorted Arrays

标签:

原文地址:http://www.cnblogs.com/li-daphne/p/5612240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!