【LeetCode】4. Median of Two Sorted Arrays 【未完待续】

本文探讨了两个有序数组中位数的求解方法。提出了两种算法实现:一种为归并排序后的直接查找(时间复杂度O(m+n)),另一种则是在O(log(m+n))时间复杂度内完成的更高效解决方案。

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

题目:

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.

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

 

描述:

给出两个有序数组,求两个数组的中位数,要求使用的解法算法复杂度为O( log (m+n) )

 

分析:

按照常规方法,能在线性时间内(O (m+n) )解决问题:使用归并排序后再求中位数(本题的后台数据比较弱,可以水过去),但是题目有复杂度要求...

看到题目要求的时间复杂度,就能想到用二分(之前遇到过一道类似的题目,用的二分解决的问题),但是构思了很久,还是控制不好算法的具体细节,无从下手....

虽然也搜索题解看了一下,但是确实没能完全理解,后边再说吧,先留个坑...

 

代码一:(时间复杂度 O(m+n))

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
       auto result = merge(nums1, nums2);
       auto mid = (result.size() - 1) >> 1;
       if (result.size() & 1) {
       		return result[mid];
	   } else {
	   		return (result[mid] + result[mid + 1]) / 2.0;
	   } 
    }
    vector<int> merge(vector<int>& nums1, vector<int>& nums2) {
    	vector<int> result;
    	int index1 = 0, index2 = 0;
    	while (index1 < nums1.size() && index2 < nums2.size()) {
    		if (nums1[index1] < nums2[index2]) {
    			result.push_back(nums1[index1]);
    			++ index1;
			} else {
				result.push_back(nums2[index2]);
				++ index2;
			}
		}
		while (index1 < nums1.size()) {
			result.push_back(nums1[index1]);
			++ index1;
		}
		while (index2 < nums2.size()) {
			result.push_back(nums2[index2]);
			++ index2;
		}
		return result;
	}
};

代码二:(时间复杂度 O( log (m+n) ))

//待后续补充

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值