当前位置:网站首页>每日一题-寻找两个正序数组的中位数-0713
每日一题-寻找两个正序数组的中位数-0713
2022-08-05 05:17:00 【菜鸡程序媛】
题目:
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
这个题,目前还不是很理解,为了速度,先背了…
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if(nums1.length > nums2.length)
return findMedianSortedArrays(nums2, nums1);
int m = nums1.length;
int n = nums2.length;
int left = 0, right = m;
int mid1 = 0, mid2 = 0;
while(left <= right){
int i = (left + right) / 2;
int j = (m + n + 1) / 2 - i;
int nums_im1 = i == 0 ? Integer.MIN_VALUE : nums1[i - 1];
int nums_i = i == m ? Integer.MAX_VALUE : nums1[i];
int nums_jm1 = j == 0 ? Integer.MIN_VALUE : nums2[j - 1];
int nums_j = j == n ? Integer.MAX_VALUE : nums2[j];
if(nums_im1 < nums_j){
mid1 = Math.max(nums_im1, nums_jm1);
mid2 = Math.min(nums_i, nums_j);
left = left + 1;
}else{
right = right - 1;
}
}
return (m + n) % 2 == 0 ? (mid1 + mid2) / 2.0 : mid1;
}
}
边栏推荐
猜你喜欢

framebuffer应用编程及文字显示(2)
![[Pytorch study notes] 11. Take a subset of the Dataset and shuffle the order of the Dataset (using Subset, random_split)](/img/59/ce3e18f32c40a97631f5ac1b53662a.png)
[Pytorch study notes] 11. Take a subset of the Dataset and shuffle the order of the Dataset (using Subset, random_split)

每日一题-单调栈

LeetCode刷题之第55题
![[Database and SQL study notes] 8. Views in SQL](/img/22/82f91388f06ef4f9986bf1e90800f7.png)
[Database and SQL study notes] 8. Views in SQL

网管日记:故障网络交换机快速替换方法

Detailed explanation of BroadCast Receiver (broadcast)

(oj)原地移除数组中所有的元素val、删除排序数组中的重复项、合并两个有序数组

网络ID,广播地址,掩码位数计算

LeetCode刷题之第746题
随机推荐
读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping
GIS面试问题
电子产品量产工具(5)- 页面系统实现
Polygon计算每一个角的角度
HuiFer 带你读懂 BeanFactory getBean 方法
CVPR 2020 - 频谱正则化
CVPR2020 - 自校准卷积
UiPath简介
八、请求处理之自定义类型参数绑定原理
OSPF网络类型
浅谈遇到的小问题
栈的应用——力扣 20.有效的括号
【UiPath2022+C#】UiPath变量和参数
LeetCode刷题之第33题
【ts】typescript高阶:条件类型与infer
C语言—三子棋的实现
MySQL主从复制—有手就能学会的MySQL集群搭建教程
Jupyter notebook选择不同的Anaconda环境作为内核运行
五、请求处理—Rest映射是怎样实现的?
单片机按键开发库-支持连击、长按等操作