|
| 1 | +/** |
| 2 | + * 4. Median of Two Sorted Arrays |
| 3 | + * https://leetcode.com/problems/median-of-two-sorted-arrays/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are two sorted arrays nums1 and nums2 of size m and n respectively. |
| 7 | + * |
| 8 | + * Find the median of the two sorted arrays. |
| 9 | + * The overall run time complexity should be O(log (m+n)). |
| 10 | + * |
| 11 | + * You may assume nums1 and nums2 cannot be both empty. |
| 12 | + */ |
| 13 | + |
| 14 | +/** |
| 15 | + * @param {number[]} nums1 |
| 16 | + * @param {number[]} nums2 |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var findMedianSortedArrays = function(nums1, nums2) { |
| 20 | + const total = nums1.length + nums2.length; |
| 21 | + const limit = Math.floor(total / 2) + 1; |
| 22 | + let i = 0, j = 0, prev, last |
| 23 | + |
| 24 | + while(i + j < limit) { |
| 25 | + if (last !== undefined) { |
| 26 | + prev = last; |
| 27 | + } |
| 28 | + if (nums1[i] < nums2[j] || j === nums2.length) { |
| 29 | + last = nums1[i++]; |
| 30 | + } else { |
| 31 | + last = nums2[j++]; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + return total % 2 === 0 ? (prev + last) / 2 : last; |
| 36 | +}; |
| 37 | + |
| 38 | +// shorter/readable alternative with higher time complexity: |
| 39 | +/** |
| 40 | + * @param {number[]} nums1 |
| 41 | + * @param {number[]} nums2 |
| 42 | + * @return {number} |
| 43 | + */ |
| 44 | +var findMedianSortedArrays = function(nums1, nums2) { |
| 45 | + const sorted = [...nums1, ...nums2].sort((a, b) => a - b); |
| 46 | + const index = Math.floor((sorted.length - 1) / 2); |
| 47 | + return sorted.length % 2 === 0 |
| 48 | + ? (sorted[index] + sorted[index + 1]) / 2 |
| 49 | + : sorted[index]; |
| 50 | +}; |
0 commit comments