《leetcode》:Find Median from Data Stream
2016-07-19 18:41
441 查看
题目
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.Examples:
[2,3,4] , the median is 3
[2,3], the median is (2 + 3) / 2 = 2.5
Design a data structure that supports the following two operations:
void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
For example:
add(1) add(2) findMedian() -> 1.5 add(3) findMedian() -> 2
思路一:超时
借用一个List来保存数据,而findMedian函数的实现是先对List进行排序,然后进行取中间值。由于没取一次中间值就要排一次序,因此,报超时也是正常的。实现代码如下:
public class MedianFinder { private List<Integer> list = new ArrayList<Integer>(); // Adds a number into the data structure. public void addNum(int num) { list.add(num); } // Returns the median of current data stream public double findMedian() { Collections.sort(list); int len = list.size(); return (len&0x01)==1?list.get(len/2):(list.get(len/2)+list.get(len/2-1))*1.0/2; } }
思路二
还是借用一个List来保存数据,只是保存数据的时候是按照升序来保存的,即在保存数据的时候,先找到其在List中要插入的位置,然后保存进行就保证了List永远是排序的。这样,在调用findMedian时,就直接取出List中的中间的值即可。
public class MedianFinder { private List<Integer> list = new ArrayList<Integer>(); // Adds a number into the data structure. public void addNum(int num) { int len = list.size(); //先处理三种特殊情况 if(len==0){ list.add(num); return ; } if(num>=list.get(len-1)){ list.add(num); return; } if(num<list.get(0)){ list.add(0, num); return ; } //利用二分查找找到num要插入的位置 int left = 0; int right = len-1; int mid = -1; while(left<=right){ mid = left + (right-left)/2; int val = list.get(mid); if(val==num){ left = mid; break; } else if(val<num){//找到第一个大于num的数 left = mid+1; } else if(val>num){ right = mid-1; } } //left指向就是要插入的位置 list.add(left, num); } // Returns the median of current data stream public double findMedian() { //Collections.sort(list); int len = list.size(); return (len&0x01)==1?list.get(len/2):(list.get(len/2)+list.get(len/2-1))*1.0/2; } }; // Your MedianFinder object will be instantiated and called as such: // MedianFinder mf = new MedianFinder(); // mf.addNum(1); // mf.findMedian();
相关文章推荐
- 第二天:校验和、mkv210_image.c等
- c_str()的介绍与用法
- linux使用yum更新或安装最新版本的mysql
- java.util.Date和java.sql.Date的区别及相互转化【转】
- jquery如何判断滚动条滚到页面底部并执行事件
- mysql 基础操作全覆盖(适用与兼职DBA,不定期更新) 推荐
- ListView图片加载错乱01
- hdu5723 Abandoned country(最小生成树+期望)(2016多校第一场A题)
- csss中box-sizing的问题 元素在另一个元素中框框包含的问题
- HDU 5726 GCD
- 直接在docker下体验强大的构建平台Quickbuild
- shell脚本攻略- grep 文本查找总结
- 作为C++小白为看懂算法题C++代码的简单语法整理
- 利用eclipse的git插件EGit与git@osc交互
- AutoLayout之intrinsicContentSize,Content Hugging Priority,Content Compression Resistance Priority
- 弹出的框,我随着窗口而下拉下来。
- Android 多进程通讯之 AIDL
- struts2标签库,Ajax标签库
- java 实现断点下载
- [Go语言]我的第一个Go语言程序