[leetcode] #4 Median of Two Sorted Array
来源:互联网 发布:自考软件哪个好 编辑:程序博客网 时间:2024/06/04 08:15
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)).
题目要求是找到两个已排序的序列A和B的中位数(如果m+n是偶数,那么则是两个数的均值)。
这道题真是让我悲喜交加。
比较幸运的是4月1号晚上在六教无聊刷题时刷到了这道题,当晚花了半个多小时写出了下面这个挫代码,然后4月2号阿里的笔试题附加题第一题就是这个……
但悲剧的是昨天查询笔试结果的时候发现被拒了。附加题里面两道编程题应该没问题,想来问题就出在前面选择题上了,时间没把握好,好多很容易算的数学题因为前面那些不了解的Java、HTML等耽误了时间跪了……
下面这段是最初为了结果生写出来的,没做什么优化(也许是因为这个被阿里拒了?)。
很容易想到要用归并排序来做,也就是拿A和B的头比较,哪个小,过哪个,一直到中值那个。需要特别注意的情况是A特别短而B特别长的情况,这种情况下遍历完了A也尚且没有找到中位数,就需要额外处理(但这种情况下就可以直接计算中位数的位置)。
比较麻烦的是m+n是偶数的情况,你得记录两个值。
class Solution {public: double findMedianSortedArrays(int A[], int m, int B[], int n) { int c[m+n]; int a=0,b=0; int median=(m+n)/2; for (;a+b<=median;) { if (A[a]<B[b]) { c[a+b]=A[a]; a++; } else if (A[a]>B[b]) { c[a+b]=B[b]; b++; } else { c[a+b]=A[a]; c[a+b+1]=A[a]; } } if (a==m&&b<n) { if (median-a-b>=0) { f=B[median-a]; if (median-a-1-b>=0) s=B[median-1-a]; } } else if (b==n&&a<m) { if (median-b-a>=0) { f=A[median-b]; if (median-a-b-1>=0) s=A[median-1-b]; } } return (m+n)%2?double(f):double(s+f)/2; }};
今天拿出来重看了一下,A和B比较的时候根本不需要处理相等的情况好么……
double findMedianSortedArrays(int A[], int m, int B[], int n) { int a=0,b=0,median=(m+n)/2; int f,s; while (a!=m&&b!=n) { if (A[a]<B[b]) { if (a+b==median) { s=A[a]; return (m+n)%2?(double)s:(double)(s+f)/2; } f=A[a++]; } else { if (a+b==median) { s=B[b]; return (m+n)%2?(double)s:(double)(s+f)/2; } f=B[b++]; } } if (a==m) { if (a+b<median) f=B[median-a-1]; s=B[median-a]; } else { if (a+b<median) f=A[median-b-1]; s=A[median-b]; } return (m+n)%2?(double)s:(double)(s+f)/2;}
但使用归并排序的代码虽然能通过测试,但是复杂度并没有达到O(log(m+n))的要求,是O(m+n)的。
既然说了要达到log(m+n),还是已经排好序的,显然是要用二分查找的方法了。
思路已经有了,挖个坑有时间再填。
0 0
- LeetCode 4: Median Of Two Sorted Array
- [leetcode] #4 Median of Two Sorted Array
- Leetcode - Median of Two Sorted Array
- Median of Two Sorted Array---LeetCode
- LeetCode:Median of two sorted array
- Leetcode--Median of Two Sorted Array
- [Leetcode]Median of two sorted array
- [LeetCode]Median of Two Sorted Array
- Median of Two Sorted Array leetcode java
- Median of Two Sorted Array leetcode java
- Median of Two Sorted Array
- Median of two sorted array
- median of two sorted array
- median of two sorted array
- Median of two sorted array
- Leetcode 4 Median of Two Sorted Arrays
- LeetCode 4 - Median of Two Sorted Arrays
- Leetcode 4 Median of Two Sorted Arrays
- 提高UITableView滚动流畅性的一些技巧
- 深搜 nyoj 43 24 Point game
- IOS开发 UI篇 APP主流UI框架结构
- 使用JackSon反序列化,封装数据
- 今天终于开博了
- [leetcode] #4 Median of Two Sorted Array
- 阀门电动执行器——只买对的,不买贵的
- 工业检测之图像匹配
- SDL,FFMPEG在iOS平台的使用
- HTMLPOST和GET编码问题(深入篇)
- 词法“陷阱”00
- 约数个数 --- 蓝桥杯
- 堆排序分析及优化
- android EditText输入限制