LeetCode-4. Median of Two Sorted Arrays

本文详细解析了LeetCode上的第4题——寻找两个有序数组的中位数,并提供了分治算法实现的具体步骤及代码示例。

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

LeetCode-4. Median of Two Sorted Arrays

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

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                                                                           

此题采用分治算法最优,将nums1和nums2进行分割,得到left_part和right_part

      left_part                      |        right_part
nums1[0], nums1[1], ..., nums1[i-1]  |  nums1[i], nums1[i+1], ..., nums1[m-1]
nums2[0], nums2[1], ..., nums2[j-1]  |  nums2[j], nums2[j+1], ..., nums2[n-1]

使得

1) len(left_part) == len(right_part)
2) max(left_part) <= min(right_part)
为了保证以上条件,必须确保
(1) i + j == m - i + n - j (or: m - i + n - j + 1)
    if n >= m, we just need to set: i = 0 ~ m, j = (m + n + 1)/2 - i
(2) nums2[j-1] <= nums1[i] and nums1[i-1] <= nums2[j]

具体的思路见leetcode解法

class Solution
{
	double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
	{
		int m = nums1.size(), n = nums2.size();
		if (m > n)return findMedianSortedArrays(nums2, nums1);
		int i, j, imin = 0, imax = m, half = (m + n + 1) / 2;
		while (imin <= imax)
		{
			 i = (imin + imax) / 2;
			 j = half - i;
			 if (i<imax&&nums2[j - 1]>nums1[i])imin = imin + 1;  
			 else if (i > imin&&nums1[i - 1] > nums2[j])imax = imax - 1; 
			 else
			 {
				 int maxLeft = 0;
				 if (i == 0)maxLeft = nums2[j - 1];
				 else if (j == 0)maxLeft = nums1[i - 1];
				 else maxLeft = max(nums2[j - 1], nums1[i - 1]);
				 if ((m + n) % 2 == 1)return maxLeft;

				 int minRight = 0;
				 if (i == m)minRight = nums2[j];
				 else if (j == n)minRight = nums1[i];
				 else minRight = min(nums2[j], nums1[i]);
				 return (maxLeft + minRight) / 2.0;

			 }
		}
		return -1;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值