[ LeetCode ] 4. Median of Two Sorted Arrays (C++ & Python)

题目: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)).

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(m+n)

,题目保证所给的两个数组不会全部为空。

 

分析

  1. 第一种思路:这里我们使用python magic,从而快速解决这个问题,直接num1,num2合并,然后排序输出。见Python Magic Code1
  2. 第二种思路:题目要求时间复杂度为O(m+n),即两个数组需要一次遍历然后给出结果,那么 最直接的思路为:使用插入排序 合并两个有序数组,然后输出中间位置即可。见Code2。
  3. 第三种思路:使用二分搜索,时间复杂度为O(log(min(m,n)); 即使用二分法查找,而非简单的全部遍历一次。也是本题所提供的一种思路。见Code Binary Search & C++。
  4. 使用python复现第二种思路。见 Code & Binary Search & Python

     

 

针对第一种思路,我们先使用python简单快捷实现

Python Magic & Code1

class Solution(object):
    def findMedianSortedArrays(self, num1, num2):
        num1.extend(num2)
        num1.sort()
        return num1[len(num1)//2] if len(num1)%2==1 else (num1[len(num1)//2-1] + num1[len(num1)//2])/2.

结果:

Runtime: 88 ms, faster than 96.75% of Python3 online submissions for Median of Two Sorted Arrays.

Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Median of Two Sorted Arrays.

针对上面这种解法,如果我们使用C++会是怎样呢?代码见下。

C++ MergeSort & Code1

class Solution {
	public:
	    double findMedianSortedArrays(vector<int>& num1, vector<int>& num2) {
			vector<int> ans;
			merge(num1.begin(), num1.end(), num2.begin(), num2.end(), back_inserter(ans));
			if(ans.size()%2){
				return ans[ans.size()/2];
			}
			return (ans[ans.size()/2-1]+ans[ans.size()/2])/2.0;
        }
};

结果:

Runtime: 48 ms, faster than 44.61% of C++ online submissions for Median of Two Sorted Arrays.

Memory Usage: 22.3 MB, less than 100.00% of C+

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值