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

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

分析

这道题是找两个排序向量的中位数,还要求了时间复杂度。这道题其实有一个取巧的做法,把这两个向量使用memcpy拷贝到一个更大空间的向量中,然后对向量进行排序,最后判断元素奇偶就可以直接输出中位数了。这个算法的时间复杂度就在于排序。如果使用sort,虽然理论平均时间复杂度比题目要求的高,但是因为之前向量已经是排序过了,所以实际运行时间并不会很长。因为sort并不只是快速排序算法,是由很多排序算法组合到一起实现的。

在实现时,还需要注意判断输入是否为空。另外,对于memcpy函数的输入是void*,也就是需要输入地址。对于数组来说,数组名就是首地址,那么vector的地址是什么呢?vector中有一个函数data,就是用来获取容器的首地址。

AC代码如下:

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
    	int m = nums1.size();
    	int n = nums2.size();
        vector<int> a(m+n);//新容器
        if(m != 0)//判断输入是否为空
        {
        	memcpy(a.data(), nums1.data(), sizeof(int)*m);//内存拷贝
		}
		if(n != 0)//判断输入是否为空
		{
			memcpy(a.data()+m, nums2.data(), sizeof(int)*n);//内存拷贝
		}
        sort(a.begin(), a.end());
        if((m + n) % 2 == 0)//偶数
        {
        	return (double)(a[(m+n)/2] + a[(m+n)/2-1])/2;
		}
		else//奇数
		{
			return a[(m+n)/2];
		}
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值