[LeetCode] 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)).
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
Thought process:
If the arrays are combined into one sorted array, the number we're looking for will be at index (m + n) / 2, or ((m + n) / 2 - 1 + (m + n) / 2) / 2. The numbers before the median in the combined array will consist of some numbers from nums1, and some numbers from nums2.
Assume half of the (m + n) / 2 numbers are from nums1, and the other half is from nums2. Say i = (m + n) / 2, we compare nums1[i / 2] with nums2[i / 2]. If nums1[i / 2] < nums2[i / 2], then we're sure that the numbers before nums1[i / 2] will not contain the median that we're looking for.
To avoid off-by-one errors and stack overflow, we'll make i represent the ith largest element, instead of the index.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int m = nums1.length; int n = nums2.length; if ((m + n) % 2 == 0) { return (findMedianSortedArrays(nums1, 0, nums2, 0, (m + n) / 2) + findMedianSortedArrays(nums1, 0, nums2, 0, (m + n) / 2 + 1)) / 2.0; } else { return findMedianSortedArrays(nums1, 0, nums2, 0, (m + n) / 2 + 1); } } private int findMedianSortedArrays(int[] nums1, int start1, int[] nums2, int start2, int target) { if (start1 >= nums1.length) { return nums2[start2 + target - 1]; } if (start2 >= nums2.length) { return nums1[start1 + target - 1]; } if (target == 1) { return Math.min(nums1[start1], nums2[start2]); } int num1 = start1 + target / 2 > nums1.length ? Integer.MAX_VALUE : nums1[start1 + target / 2 - 1]; int num2 = start2 + target / 2 > nums2.length ? Integer.MAX_VALUE : nums2[start2 + target / 2 - 1]; int remain = target - target / 2; if (num1 < num2) { return findMedianSortedArrays(nums1, start1 + target / 2, nums2, start2, remain); } else { return findMedianSortedArrays(nums1, start1, nums2, start2 + target / 2, remain); } } } |
Time complexity: O(log(m + n)).
Comments
Post a Comment