<LeetCode>寻找两个有序数组的中位数

题目

给定两个大小为m和n的有序数组nums1和nums2.
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为O(log(m + n))。
你可以假设nums1和nums2不会同时为空。

题目解法

#include <stdio.h>
#include <vector>
using namespace std;
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
class Solution {
public:    
	double findMedianSortedArrays(vector<int>& nums1, 
	vector<int>& nums2) {        
		int n = nums1.size();        
		int m = nums2.size();        
		if (n > m)  //保证数组1一定最短        
		{            
			return findMedianSortedArrays(nums2, nums1);        		}        
		// Ci 为第i个数组的割,比如C1为2时表示第1个数组只有2个元素。        		//LMaxi为第i个数组割后的左元素。RMini为第i个数组割后的右元素。
        	int LMax1, LMax2, RMin1, RMin2, c1, c2, lo = 0, hi = 2 * n;         		//我们目前是虚拟加了'#'所以数组1是2*n长度        
        	while (lo <= hi)   //二分        
        	{            
        		c1 = (lo + hi) / 2;  //c1是二分的结果            
        		c2 = m + n - c1;
			LMax1 = (c1 == 0) ? INT_MIN : nums1[(c1 - 1) / 2];            			
			RMin1 = (c1 == 2 * n) ? INT_MAX : nums1[c1 / 2];             
			LMax2 = (c2 == 0) ? INT_MIN : nums2[(c2 - 1) / 2];            
			RMin2 = (c2 == 2 * m) ? INT_MAX : nums2[c2 / 2];
			if (LMax1 > RMin2)                
				hi = c1 - 1;            
			else if (LMax2 > RMin1)                
				lo = c1 + 1;            
			else                
				break;        
		}        
		return (max(LMax1, LMax2) + min(RMin1, RMin2)) / 2.0;    
	}
};
int main(int argc, char *argv[])
{
 vector<int> nums1 = { 2,3, 5 };
 vector<int> nums2 = { 1,4,7, 9 };
 
 Solution solution;
 double ret = solution.findMedianSortedArrays(nums1, nums2);
 return 0;
}	
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值