英文题目
Median of Two Sorted Arrays
两个数组的中值
here are two sorted arrays nums1 and nums2 of size m and n respectively.
这又两个有序的数组 nums1 和nums2 大小是m 和 n
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
找到 两个有序的数组的中值 复杂度最大是O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
你可以假设 nums1 和nums2 不同时为空
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
思路
思路一 合并数组
合并数组 然后 直接取中间的值 如果是奇数 中间数 如果是偶数 中间两数的除以2 O(m+n) 不给过
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int len = m+n;
int result[] = new int[len];
while(m > 0 && n > 0){
if(nums1[m-1] > nums2[n-1]){
result[m+n-1] = nums1[m-1];
m--;
}else{
result[m+n-1] = nums2[n-1];
n--;
}
}
while(m > 0){
result[m+n-1] = nums1[m-1];
}
while(n > 0){
result[m+n-1] = nums2[n-1];
}
if(len % 2 == 0){
return result[len/2-1]+result[len/2];
}else{
return result[len/2];
}
}
}
思路二 二分法
二分法
将一个集合划分为两个长度相等的子集,其中一个子集中的元素总是大于另一个子集中的元素。
len(left_part)=len(right_part)max(left_part)≤min(right_part)
中位数也是中值
左右两部分进行分类
- 左右个数条件: 将左右分为两部分 左边的比右边的都小
并且左边个数和右边个数为
如果m+n 为偶数 则 左右两边一样
如果m+n 为奇数 则 左边 = 右边 + 1
条件翻译成结果即为: i + j = m-i + n -j 或者 i + j = m -i + n -j + 1
j = (m+n+1)/2 -i; - 同步保证:a[i-1] < a[j] 和 a[j-1]< a[i];
- 找到 左边最大 和右边最小 是奇数 结果为左边最大 是偶数 左边最大和右边最小的平均值
- 如果 a[i-1] < b[j] 并且 b[j-1] < a[i] 找到合适的
- 如果 b[j-1] > a[i] a[i] 比较小 增大a[i] 搜索范围是 [i+1,imax];
- 如果 a[i-1] > b[j] a[i-1] 太大 需要减小 i 搜索范围是 [imin , i -1];
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m =nums1.length;
int n = nums2.length;
if(m > n){// 保证 m <= n
int [] temp = nums1; nums1 = nums2; nums2 = temp;
int tmp = m ; m = n; n = tmp;
}
int iMin = 0, iMax = m, halfLen = (m + n + 1)/2;// 如果 m+ n 为奇数 加1 补为偶数 如果是偶数 没有影响
while(iMin <= iMax){
int i = (iMin + iMax) /2;
int j = halfLen - i;
if (i < iMax && nums2[j-1] > nums1[i]){
iMin = i + 1;
}else if (i > iMin && nums1[i-1] > nums2[j]) {
iMax = i - 1;
}else{
int maxLeft = 0;
if (i == 0) { maxLeft = nums2[j-1]; }
else if(j==0){ maxLeft = maxLeft = nums1[i-1]; }
else { maxLeft = Math.max(nums1[i-1],nums2[j-1]); }
if((m+n)%2==1){return maxLeft;}
int minRight = 0;
if (i == m) { minRight = nums2[j]; }
else if(j==n){ minRight = nums1[i]; }
else { minRight = Math.min(nums1[i],nums2[j]); }
return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
}
参考官方
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。