4. Median of Two Sorted Arrays, Hard
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)).
Solution, Typescript
function findMedianSortedArrays(nums1: number[], nums2: number[]): number {let medianIdx = [];let totalCount = nums1.length + nums2.length;let firstMedianIdx = Math.floor(totalCount / 2);if(totalCount % 2 == 0) {medianIdx.push(firstMedianIdx-1);medianIdx.push(firstMedianIdx);} else {medianIdx.push(firstMedianIdx);}var medianArr = [];var num1Idx = 0;var num2Idx = 0;for(var i = 0; i < totalCount; i++) {var value = 0;var isNum1 = true;if(num1Idx < nums1.length && num2Idx < nums2.length) {isNum1 = nums1[num1Idx] < nums2[num2Idx];} else {isNum1 = num2Idx >= nums2.length;}if(isNum1) {value = nums1[num1Idx];num1Idx++;} else {value = nums2[num2Idx];num2Idx++;}if(i == medianIdx[0]) {medianArr.push(value);medianIdx.shift();}if(medianIdx.length == 0) {break;}}var median = 0;for(var i = 0; i < medianArr.length; i++) {median += medianArr[i];}median = median / medianArr.length;return median;};
I'm surprised this is considered hard, but maybe it is just me.