Java recursive Solution, don't know why time limited. I'm so confused


  • 0
    D
        public double findMedianSortedArrays(int[] nums1, int[] nums2) {
            int length = nums1.length+nums2.length;
            int k = (length+1)/2;
            double kth = findKth(nums1,0,nums2,0,k);
            if(length%2==0){
                return (kth+findKth(nums1,0,nums2,0,k+1))/2.0;
            }else{
                return kth;
            }
        }
        public double findKth(int a[],int startA,int[] b,int startB,int k){
            //when to stop
            if(startA>a.length-1){
                return b[startB+k-1];
            }
            if(startB>b.length-1){
                return a[startA+k-1];
            }
            if(k == 1){
                return Math.min(a[startA],b[startB]);
            }
            //update startA and startB
            int midA = startA+k/2-1;
            int midB = startB+k/2-1;
            if(midA>a.length-1) midA = a.length-1;
            if(midB>b.length-1) midB = b.length-1;
            
            if(a[midA]<b[midB]){
                k = k-(midA-startA+1);
                startA = midA+1;
            }else{
                k = k-(midB-startB+1);
                startB = midB+1;
            }
            return findKth(a,startA,b,startB,k);
        }
    }
    

Log in to reply
 

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