算法—两个有序数组的中位数 Median of Two Sorted Arrays
关注微信公众号:CodingTechWork,一起学习进步。
题目
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。
请你找出这两个正序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 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
题解
1 暴力求解
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
//定义一个新的数组存放两个数组的值
int[] newNums = new int[nums1.length + nums2.length];
for (int i = 0; i < nums1.length; i++) {
newNums[i] = nums1[i];
}
for (int j = 0; j < nums2.length; j++) {
newNums[nums1.length + j] = nums2[j];
}
//排序
Arrays.sort(newNums);
//个位数判断,直接返回中间值
if (newNums.length % 2 == 1) {
return newNums[newNums.length / 2];
} else { //偶数判断,返回length/2 -1及length/2和的一半
return (newNums[newNums.length / 2 - 1] + newNums[newNums.length / 2]) / 2.0;
}
}
}
当然,时间复杂度为o(m+n)
,这是不满足题目需求的o(log(m+n))
2 二分法
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length;
int m = nums2.length;
int left = (n + m + 1) / 2;
int right = (n + m + 2) / 2;
//将偶数和奇数的情况合并,如果是奇数,会求两次同样的 k 。
return (getMinK(nums1, 0, n - 1, nums2, 0, m - 1, left) + getMinK(nums1, 0, n - 1, nums2, 0, m - 1, right)) * 0.5;
}
public static int getMinK(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2, int k) {
int length1 = end1 - start1 + 1;
int length2 = end2 - start2 + 1;
if (length1 > length2) {
//短的在前,保证先为空的为length1
return getMinK(nums2,start2,end2,nums1,start1,end1,k);
}
//说明nums1已经为空,此时返回nums2的元素
if (length1 == 0) {
return nums2[start2 + k -1];
}
if (k == 1) {
return Math.min(nums1[start1], nums2[start2]);
}
int i = start1 + Math.min(length1, k / 2) - 1;
int j = start2 + Math.min(length2, k / 2) -1;
if (nums1[i] > nums2[j]) {
return getMinK(nums1, start1, end1, nums2, j + 1, end2, k - (j - start2 + 1));
} else {
return getMinK(nums1, i + 1, end1, nums2, start2, end2, k - (i - start1 + 1));
}
}
}
烧不死的鸟就是凤凰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)