LeetCode——Median of Two Sorted Arrays

本文探讨如何在O(log(m+n))的时间复杂度内找到两个已排序数组的中位数,介绍了一种高效的算法,并提供了一个C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode——Median of Two Sorted Arrays

leetcode上第四题:

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)).

题目翻译:

给定两个已经排序过的数组,求这两个数组中的中位数,要求时间复杂度为O(log (m+n)).

<span style="font-size:14px;">#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) 
{
	int n = nums1.size();
	int m = nums2.size();
	vector<int> num3;
	num3.insert(num3.end(),nums1.begin(),nums1.end());
	num3.insert(num3.end(),nums2.begin(),nums2.end());
	sort(num3.begin(),num3.end());
	int k = n+m;
	double target = (double) (k%2?num3[k/2]:(num3[k/2]+num3[k/2-1])/2.0);
	return target;     
}
int main()
{
	int a[] = {3,7,8};
	int b[] = {2,6,9};
	vector<int> s1(a,a+3);
	vector<int> s2(b,b+3);
	double tar = findMedianSortedArrays(s1,s2);
	cout<<tar<<endl;
	return 0;
}</span>
其实此方法在最坏的情况下是O (n log n),但是题目中说过已经两个数组都是已经排过序的,所以可以勉强达到leetcode平台的要求吧(个人感觉检查不够严格)

已经想到了一种时间复杂度为O(log (m+n))的算法:我们可以算出中位数元素在所有元素中是第几个记为n,因为两个数组是已经排好序的,所以不断的比较两个数组的元素,直到数量达到n,记录该元素(对于奇数个就可以返回值了,对于偶数个需要再求出下一个)。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值