leetcode 004 —— Median of Two Sorted Arrays
来源:互联网 发布:人工智能顶级杂志 编辑:程序博客网 时间:2024/06/04 20:06
There are two sorted arrays A and B 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)).
归并排序题
方法一:先合并数组,在排序,在搜索中间值。(繁琐)
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int *a=new int[m+n]; memcpy(a,A,sizeof(int)*m); memcpy(a+m,B,sizeof(int)*n); sort(a,a+n+m); double median=(double) ((n+m)%2? a[(n+m)>>1]:(a[(n+m-1)>>1]+a[(n+m)>>1])/2.0); delete a; return median; }};
方法二:可以用一个计数器,记录当前已经找到第m 大的元素了。同时我们使用两个指针pA 和pB,分别指向A 和B 数组的第一个元素,使用类似于merge sort 的原理,如果数组A 当前元素小,那么pA++,同时m++;如果数组B 当前元素小,那么pB++,同时m++。最终当m 等于k 的时候,就得到了我们的答案,O(k) 时间,O(1) 空间。但是,当k 很接近m + n 的时候,这个方法还是O(m + n) 的。
方法三:
0 0
- LeetCode — Median of Two Sorted Arrays
- LeetCode—Median of Two Sorted Arrays
- leetcode—Median of Two Sorted Arrays
- leetcode 004 —— Median of Two Sorted Arrays
- leetcode-004:Median of Two Sorted Arrays
- [LeetCode]-004-Median of Two Sorted Arrays
- 004 Median of Two Sorted Arrays [Leetcode]
- [LeetCode]004-Median of Two Sorted Arrays
- Leetcode 004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays *
- leetcode-004 Median of Two Sorted Arrays
- LeetCode 004 Median of Two Sorted Arrays
- LeetCode-004 Median of Two Sorted Arrays
- leetcode 004 Median of Two Sorted Arrays
- LeetCode —— Median of Two Sorted Arrays
- LeetCode——Median of Two Sorted Arrays
- LeetCode——Median of Two Sorted Arrays
- LeetCode题解——4Median of Two Sorted Arrays
- textField输入内容分限制为手机号
- (六)场景法
- php 根据两地经纬度计算距离,单位可调节。
- tomcat实现容器内认证
- Android开发 必备技术网站 推荐
- leetcode 004 —— Median of Two Sorted Arrays
- phonegap运行www包遇到的问题
- shell中的$? $0 $@ $* $#
- 解决ie浏览器注册事件不兼容问题
- 【深度学习系列4】深度学习及并行化实现概述
- JavaScript动态设置滚动条高度
- unset 数组 json_encode 数据格式
- android获取系统权限小记
- Myeclipse 2015 stable 1.0 完美破解方法