注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
请教大神,不知道17-22行哪里出了问题,总是取不到奇数情况的中间数,用的test case是["MedianFinder","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian","addNum","findMedian"][[],[-1],[],[-2],[],[-3],[],[-4],[],[-5],[]]
代码如下:
- class MedianFinder {
- PriorityQueue<Integer> pq;
- /** initialize your data structure here. */
- public MedianFinder() {
- pq = new PriorityQueue<>();
- }
-
- public void addNum(int num) {
- pq.add(num);
- }
-
- public double findMedian() {
- int n = pq.size();
- double res = 0.0;
- Iterator iter = pq.iterator();
- Integer tmp = 0;
- if (n % 2 != 0) {
- for (int i = 0; i < n/2; i++) {
- iter.next();
- }
- tmp = (Integer) iter.next();
- res = (double) tmp;
- } else {
- for (int i = 0; i < n/2; i++) {
- tmp = (Integer) iter.next();
- }
- Integer x = (Integer) iter.next();
- res = ((double) tmp + (double) x)/2;
- }
- return res;
- }
- }
- /**
- * Your MedianFinder object will be instantiated and called as such:
- * MedianFinder obj = new MedianFinder();
- * obj.addNum(num);
- * double param_2 = obj.findMedian();
- */
复制代码
|