积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};

 

posted on 2016-06-23 21:18  x7b5g  阅读(204)  评论(0编辑  收藏  举报