Share my java solution


  • 0
    H
      int l1 = -1;
    int l2 = -1;
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    	int tar = (nums1.length + nums2.length);
    	if (nums1.length * nums2.length == 0) {
    		if (nums1.length == 0) {
    			if (tar % 2 == 0)
    				return (nums2[nums2.length / 2 - 1] + nums2[nums2.length / 2]) / 2.0;
    			return nums2[nums2.length / 2];
    		} else {
    			if (tar % 2 == 0)
    				return (nums1[nums1.length / 2 - 1] + nums1[nums1.length / 2]) / 2.0;
    			return nums1[nums1.length / 2];
    
    		}
    
    	}
    	
    	if (tar % 2 == 0) {
    		return (find(tar / 2 - 1, nums1, nums2) + find(0, nums1, nums2)) / 2.0;
    
    	} else {
    		return find(tar / 2, nums1, nums2);
    
    	}
    
    }
    
    public int find(int next, int[] nums1, int[] nums2) {
    
    	if (next == 0) {
    		if (l1 == nums1.length - 1) {
    			return nums2[l2++ + 1];
    		} else if (l2 == nums2.length - 1) {
    			return nums1[l1++ + 1];
    
    		}
    		return nums1[l1 + 1] > nums2[l2 + 1] ? nums2[l2++ + 1]
    				: nums1[l1++ + 1];
    
    	}
    	if (next == 1) {
    		if (nums1[l1 + 1] > nums2[l2 + 1]) {
    			l2++;
    		} else {
    			l1++;
    		}
    		return find(0, nums1, nums2);
    	} else {
    		int t1 = (next - 2) / 2 % (nums1.length - 1 - l1) + 1;
    		int t2 = (next - 2) / 2 % (nums2.length - l2 - 1) + 1;
    		if (nums1[l1 + t1] >= nums2[t2 + l2]) {
    			if (t2 + l2 == nums2.length - 1) {
    				next = next - t2;
    				l2 = t2 + l2;
    				l1 = l1 + next;
    				return nums1[l1++ + 1];
    			} else {
    				next = next - t2;
    				l2 = t2 + l2;
    				return find(next, nums1, nums2);
    
    			}
    
    		} else {
    			if (t1 + l1 == nums1.length - 1) {
    				next = next - t1;
    				l1 = t1 + l1;
    				l2 = l2 + next;
    				return nums2[l2++ + 1];
    
    			} else {
    				next = next - t1;
    				l1 = t1 + l1;
    				return find(next, nums1, nums2);
    
    			}
    
    		}
    
    	}
    
    }

Log in to reply
 

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