LeetCode 4. 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)).

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


给出两个排好序的数列,求中位数。设计一个函数用来取最小值即可很方便得到


class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int n1=nums1.size();
        int n2=nums2.size();
        if(n1==0&&n2==0)return 0.0;
        int p1=0,p2=0;
        double ans=0.0;
        int half=(n1+n2-1)/2;
        int i;
        for(i=0;i<half;i++){
            ans=getmin(nums1,nums2,&p1,&p2);
        }
        ans=getmin(nums1,nums2,&p1,&p2);
        if((n1+n2)%2==0){
            ans+=getmin(nums1,nums2,&p1,&p2);
            ans=ans/2.0;
        }
        return ans;
    }
    double getmin(vector<int>&v1,vector<int>&v2,int *p1,int *p2){
        int n1=v1.size();
        int n2=v2.size();
        if(n1==*p1){
            double ans=(double)v2[*p2];
            (*p2)++;
            return ans;
        }
        if(n2==*p2){
            double ans=(double)v1[*p1];
            (*p1)++;
            return ans;
        }
        double ans;
        if(v1[*p1]<v2[*p2]){
            ans=v1[*p1];
            (*p1)++;
            return ans;
        }
        else{
            ans=v2[*p2];
            (*p2)++;
            return ans;
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值