leetcode 4.寻找两个有序数组的中位数
2019-03-07 22:20
405 查看
题目
给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
思路
- 找中位数。不能用排序,因为排序最小时间复杂度为O(nlogn),考虑二分法。
因为是有序数组,所以我们假设从下标为i处将A数组分为两半,从下标为j处将B数组分为两半,即:
* A[0], A[1], …, A[i-1] | A[i], A[i+1], …, A[m-1]
* B[0], B[1], …, B[j-1] | B[j], B[j+1], …, B[n-1]
满足两个条件:
* 1.len(left_part)==len(right_part) 相当于 i+j=m-i+n-j,进一步推出j=(m+n)/2-i,i确定j也确定了
* 2.min(right_part)>=max(left_part) 相当于 B[j]>=A[i-1] && A[i]>=B[j-1]
- 判断数组和奇偶性
当1中条件满足时,判断数组奇偶性
如果数组之和是偶数,中位数=(max(left_part)+min(right_part))/2
如果数组之和是奇数,中位数=max(left_part)或者min(right_part)
- 处理特殊情况
首先由于j是由i决定的,j=(m+n)/2 - i, i的取值范围是0到m,也就是说j可能的值是(n-m)/2 到(m+n)/2,由于j不能为负,那么反推n>=m
i==0或者i==m时,A数组有一边是没有值的
j==0或者j==n时,B数组有一边也是没有值的
代码
/** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number} */ var findMedianSortedArrays = function(nums1, nums2) { let aLen = nums1.length, bLen = nums2.length; //判断nums1和nums2的大小 if(aLen > bLen){ let Len = aLen; aLen = bLen; bLen = Len; let nums = nums1; nums1 = nums2; nums2 = nums; } //中位数i的大小为0~aLen iMin = 0, iMax = aLen; let lenMiddle = (aLen+bLen+1)/2; while (iMin<=iMax) { let i =(iMin+iMax)/2; let j = lenMiddle-i; if(i>iMin && nums2[j] < nums1[i-1]){ iMax = i-1; } else if(i<iMax && nums1[i] < nums2[j-1]){ iMin = i+1; }else{ let maxLeft = 0; if (i == 0) { maxLeft = nums2[j - 1]; } else if (j == 0) { maxLeft = nums1[i - 1]; } else { maxLeft = Math.max(nums1[i - 1], nums2[j - 1]); } if ((aLen + bLen) % 2 == 1) { return maxLeft; } let minRight = 0; if (i == aLen) { minRight = nums2[j]; } else if (j == bLen) { minRight = nums1[i]; } else { minRight = Math.min(nums2[j], nums1[i]); } return (maxLeft + minRight) / 2; } } return; };
相关文章推荐
- 【leetcode】4. 寻找两个有序数组的中位数
- 【LeetCode】第四题:寻找两个有序数组的中位数
- [LeetCode]4. 寻找两个有序数组的中位数/C++
- leetcode 寻找两个有序数组的中位数
- LeetCode题解(python)-4. 寻找两个有序数组的中位数
- leetcode--寻找两个有序数组的中位数
- leetcode 寻找两个有序数组的中位数 median of two sorted arrays
- Python学习-Leetcode刷题记2:寻找两个有序数组的中位数
- LeetCode4.python实现:寻找两个有序数组中的中位数问题☆☆☆
- [leetcode] Median of Two Sorted Arrays 寻找两个有序数组的中位数
- Leetcode(C++)——4. 寻找两个有序数组的中位数
- Datawhale-LeetCode集训打卡-寻找两个有序数组的中位数
- Leetcode:4.寻找两个有序数组的中位数
- [leetcode 4] 寻找两个有序数组的中位数 python
- Leetcode-寻找两个有序数组的中位数
- LeetCode刷题笔记(Java版)----4. 寻找两个有序数组的中位数
- LeetCode-4 :寻找两个有序数组的中位数 ★★★★★
- 寻找两个有序数组的中位数(LeetCode)
- LeetCode--4. 寻找两个有序数组的中位数(Median of Two Sorted Arrays)
- LeetCode第4题--寻找两个有序数组的中位数