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

You may assume nums1 and nums2 cannot be both empty.

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

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        if ((len1 + len2 & 1) == 0) {
            return (findKthSortedArrays(nums1, 0, nums2, 0, (len1 + len2) / 2 ) + findKthSortedArrays(nums1, 0, nums2, 0, (len1 + len2) / 2  + 1)) / 2.0;
        } else {
            return findKthSortedArrays(nums1, 0, nums2, 0, (len1 + len2) / 2 + 1) / 1.0;
        }
   
    }
    private int findKthSortedArrays(int[] nums1, int start1, int[] nums2, int start2, int k) {
        if (nums1.length - start1 < nums2.length - start2) {
            return findKthSortedArrays(nums2, start2, nums1, start1, k);
        }
        if (nums2.length - start2 == 0) {
            return nums1[start1 + k -1];
        }

        if (k == 1) {
            return Math.min(nums1[start1], nums2[start2]) ;
        }
        int portion2 = Math.min(nums2.length - start2, k / 2);
        int portion1 = k - portion2;
        if (nums1[start1 + portion1 - 1] == nums2[start2 + portion2 - 1]) {
            return nums2[start2 + portion2 -1];
        } else if (nums1[start1 + portion1 -1] < nums2[start2 + portion2 -1]) {
            return findKthSortedArrays(nums1, start1 + portion1, nums2, start2, portion2);
        } else {
            return findKthSortedArrays(nums1, start1, nums2, start2 + portion2, portion1);
        }
        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容