当前位置:网站首页>Topic25——4. 寻找两个正序数组的中位数
Topic25——4. 寻找两个正序数组的中位数
2022-06-09 05:38:00 【_卷心菜_】
题目:给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
算法的时间复杂度应该为 O(log (m+n)) 。
示例 1:
输入:nums1 = [1,3], nums2 = [2]
输出:2.00000
解释:合并数组 = [1,2,3] ,中位数 2
示例 2:
输入:nums1 = [1,2], nums2 = [3,4]
输出:2.50000
解释:合并数组 = [1,2,3,4] ,中位数 (2 + 3) / 2 = 2.5
提示:
nums1.length == m
nums2.length == n
0 <= m <= 1000
0 <= n <= 1000
1 <= m + n <= 2000
-106 <= nums1[i], nums2[i] <= 106
归并排序思想:
当排到可以计算中位数的数量时停止排序。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int total_len = nums1.length + nums2.length; //两个数组长度总和
int mid = total_len / 2;
int[] arr = new int[mid + 1];
int count = 0;
int i = 0;
int j = 0;
while(i < nums1.length && j < nums2.length) {
if(nums1[i] < nums2[j]) {
arr[count] = nums1[i];
count++;
i++;
if(count-1 == mid)
break;
} else {
arr[count] = nums2[j];
count++;
j++;
if(count-1 == mid)
break;
}
}
for(int m = i; count <= mid && m < nums1.length; m++) {
arr[count++] = nums1[m];
}
for(int n = j; count <= mid && n < nums2.length; n++) {
arr[count++] = nums2[n];
}
if(total_len % 2 == 0) {
//当长度为偶,中位数为mid位置与mid+1的和的一半 当长度为奇,中位数为mid位置的值
return (arr[mid] + arr[mid - 1]) / 2.0;
} else {
return arr[mid];
}
}
}
边栏推荐
- “Ran out of input” while use WikiExtractor
- FPGA based TDC Research Report
- Alibaba cloud AI training camp - machine learning 3:lightgbm
- IP address division and subnet
- Remove duplicates from sort array -leetcode
- Gstreamer应用开发实战指南(二)
- redis 缓存雪崩、穿透、击穿问题
- 使用MAT进行内存问题定位
- Yolov5-6.0系列 | yolov5的模块设计
- Mining happiness with machine learning
猜你喜欢

synchronized 详细解析

Heqibao's trip to Chongqing ~

冒泡排序,打印菱形,打印直角三角形,打印倒三角,打印等边三角形,打印九九乘法表

Alibaba cloud AI training camp - SQL basics 3: complex query methods - views, subqueries, functions, etc

数据血缘用例与扩展实践

Apache Devlake 代码库导览

Yolov5-6.0 series | yolov5 model network construction

In latex, \cdots is followed by a sentence. What's wrong with the format of the following sentence.

Gstreamer应用开发实战指南(四)

Interview process and thread
随机推荐
SQL optimization notes - forward
SSL证书安装后网站还是显示不安全
Encapsulation of common methods in projects
Lambda anonymous function
对pyqt5和SQL Server数据库进行连接
Ffmpeg pulls webrtc streams, and the first all open source solution in the metartc industry is coming
latex中\cdots后面接上句子,后面的句子格式会乱怎么回事。
YOLOv5的Tricks | 【Trick7】指数移动平均(Exponential Moving Average,EMA)
[it] Fuxin PDF Keeping Tool Selection
SET DECIMAL_V2=FALSE及UDF ERROR: Cannot divide decimal by zero及Incompatible return types DECIMAL问题排查
AspNetPager combines stored procedure paging to speed up access
Connecting pyqt5 and SQL Server Databases
线程 interrupted 详细解析
function
Alibaba cloud AI training camp -sql foundation 2: query and sorting
AQS之 ReentrantLock 源码分析
AQS 之 CountdownLatch 源码分析
Enter two positive integers m and N to find their maximum common divisor and minimum common multiple.
Esmascript 6.0 advanced
3-4月份我们干了些什么?