Problem

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).

Example

  1. Input: nums1 = [1,3], nums2 = [2]
  2. Output: 2.00000
  3. Explanation: merged array = [1,2,3] and median is 2.
  1. Input: nums1 = [1,2], nums2 = [3,4]
  2. Output: 2.50000
  3. Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
  1. Input: nums1 = [0,0], nums2 = [0,0]
  2. Output: 0.00000
  1. Input: nums1 = [], nums2 = [1]
  2. Output: 1.00000

Solution

  1. var findMedianSortedArrays = function (nums1, nums2) {
  2. var len = nums1.length + nums2.length;
  3. var midIndex1 = Math.floor(len / 2);
  4. var midIndex2 = midIndex1;
  5. if (len % 2 === 0) {
  6. midIndex2 = midIndex1 - 1;
  7. }
  8. if (nums1.length === 0) {
  9. return (nums2[midIndex1] + nums2[midIndex2]) / 2;
  10. }
  11. if (nums2.length === 0) {
  12. return (nums1[midIndex1] + nums1[midIndex2]) / 2;
  13. }
  14. var arr = [];
  15. var source1 = [...nums1], source2 = [...nums2];
  16. while(arr.length <= midIndex1) {
  17. if (source1.length === 0) {
  18. let index1 = midIndex1 - arr.length;
  19. let index2 = (index1 - (midIndex1 - midIndex2));
  20. let num1 = source2[index1];
  21. let num2 = index2 >= 0 ? source2[index2] : arr[arr.length - 1];
  22. return (num1 + num2) / 2;
  23. }
  24. if (source2.length === 0) {
  25. let index1 = midIndex1 - arr.length;
  26. let index2 = (index1 - (midIndex1 - midIndex2));
  27. let num1 = source1[index1];
  28. let num2 = index2 >= 0 ? source1[index2] : arr[arr.length - 1];
  29. return (num1 + num2) / 2;
  30. }
  31. if (source1[0] < source2[0]) {
  32. arr.push(...source1.splice(0, 1));
  33. } else {
  34. arr.push(...source2.splice(0, 1));
  35. }
  36. }
  37. return (arr[arr.length - 1] + arr[arr.length - 1 - (midIndex1 - midIndex2)]) / 2;
  38. };