Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* eslint-disable no-var */
- /* eslint-disable no-unused-vars */
- /*
- * @lc app=leetcode id=4 lang=javascript
- *
- * [4] Median of Two Sorted Arrays
- */
- /**
- * @param {number[]} nums1
- * @param {number[]} nums2
- * @return {number}
- */
- var findMedianSortedArrays = function (nums1, nums2) {
- if (nums1.length > nums2.length) {
- return findMedianSortedArrays(nums2, nums1);
- }
- const xLength = nums1.length;
- const yLength = nums2.length;
- let low = 0;
- let high = xLength;
- while (low <= high) {
- const xPartition = Math.floor((low + high) / 2);
- const yPartition = Math.floor((xLength + yLength + 1) / 2 - xPartition);
- const xMaxLeft = xPartition === 0 ? Number.NEGATIVE_INFINITY : nums1[xPartition - 1];
- const xMinRight = xPartition === xLength ? Number.POSITIVE_INFINITY : nums1[xPartition];
- const yMaxLeft = yPartition === 0 ? Number.NEGATIVE_INFINITY : nums2[yPartition - 1];
- const yMinRight = yPartition === yLength ? Number.POSITIVE_INFINITY : nums2[yPartition];
- if (xMaxLeft <= yMinRight && yMaxLeft <= xMinRight) {
- if ((xLength + yLength) % 2 === 0) {
- return (Math.max(xMaxLeft, yMaxLeft) + Math.min(yMinRight, xMinRight)) / 2;
- }
- return Math.max(xMaxLeft, yMaxLeft);
- }
- if (xMaxLeft > yMinRight) {
- high = xPartition - 1;
- } else {
- low = xPartition + 1;
- }
- }
- return false;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement