My code output 0.50000 on leetcode, but print correct answer 1.00000 on my own computer, why?


  • 0
    C

    I have the same confusion with that person.

    Input: [1], [1]

    Output: 0.50000

    Expected: 1.00000

    class Solution {
    public:

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size(), n = nums2.size();
        int k1, k2;
        double res1, res2;
        k1 = (m+n+1)>>1;
        k2 = (m+n+2)>>1;
        res1 = findKthNum(nums1,nums2,k1);
        res2 = findKthNum(nums1,nums2,k2);
        return (res1+res2)/2;
    }
    
    double findKthNum(vector<int>& nums1, vector<int>& nums2, int k){
        int m = nums1.size(), n = nums2.size();
        int p1, p2, s1=0, s2=0;
        while(s1<m && s2<n && k>1){
            int num = k/2;
            p1 = min(s1+num-1,m);
            p2 = min(s2+num-1,n);
            if(nums1[p1] <= nums2[p2]){
                s1 = p1+1;
                m -= num;
            }
            else{
                s2 = p2+2;
                n -= num;
            }
            k -= num;
        }
        if(s1==m){
            return nums2[s2+k-1];
        }
        else if(s2==n){
            return nums1[s1+k-1];
        }
        else{
            return min(nums1[s1],nums2[s2]);
        }
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.