2016年7月7日星期四

[LeetCode] #4 Median of Two Sorted Arrays

1) Merge + find median O(m + n)
2) Find kth largest element in two arrays O(logk), k = (m + n)/2, because every time throw away k/2^n

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1 == null || nums2 == null) {
            return 0.0;
        }
        if ((nums1.length + nums2.length) % 2 != 0) {
            return findKthElem(nums1, nums2, 0, 0, (nums1.length + nums2.length) / 2 + 1);
        } else {
            return (findKthElem(nums1, nums2, 0, 0, (nums1.length + nums2.length) / 2) + findKthElem(nums1, nums2, 0, 0, (nums1.length + nums2.length) / 2 + 1)) / 2.0;
        }
    }
    
    private int findKthElem(int[] nums1, int[] nums2, int start1, int start2, int k) {
        if (start1 >= nums1.length) {
            return nums2[start2 + k - 1];
        }
        if (start2 >= nums2.length) {
            return nums1[start1 + k - 1];
        }
        
        if (k == 1) {
            return nums1[start1] > nums2[start2] ? nums2[start2] : nums1[start1];
        } 
        
        int value1 = start1 + k/2 - 1 < nums1.length ? nums1[start1 + k/2 - 1] : Integer.MAX_VALUE; // use max value here to throw away first k/2 elems in nums2 
        int value2 = start2 + k/2 - 1 < nums2.length ? nums2[start2 + k/2 - 1] : Integer.MAX_VALUE;
        if (value1 > value2) {
            return findKthElem(nums1, nums2, start1, start2 + k/2, k - k/2); // the rest elems to find
        } else {
            return findKthElem(nums1, nums2, start1 + k/2, start2, k - k/2);
        }
    }
}

没有评论:

发表评论