题解 | #数据流中的中位数#

数据流中的中位数

http://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1

  1. python 解法,全部列表里塞,取的时候sort一把。插入的时候时间复杂度为0,取的时候为logN,相比大小顶堆也不错嘛,哈哈。

    # -*- coding:utf-8 -*-
    class Solution:
     def __init__(self):
         self.list_num = []
         self.count = 0
    
     def Insert(self, num):
         self.list_num.append(num)
         self.count += 1
         # write code here
     def GetMedian(self):
         self.list_num.sort()
         if self.count%2:
             return self.list_num[int(self.count/2)]
         else:
             return (self.list_num[int(self.count/2)-1]+self.list_num[int(self.count/2)])/2
  2. java解法: 大顶堆存小数,小顶堆存大数,需要的时候两个堆取个顶就ok

import java.util.PriorityQueue;
import java.util.Comparator;

public class Solution {
    private PriorityQueue<Integer> minq = new PriorityQueue<>();
    private PriorityQueue<Integer> maxq = new PriorityQueue<>(new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
});
    private int count = 0;
    public void Insert(Integer num) {
        count ++;
        if(count%2==0){
            minq.offer(num);
            num = minq.poll();
            maxq.offer(num);
        }else{
            maxq.offer(num);
            num = maxq.poll();
            minq.offer(num);
        }
    }

    public Double GetMedian() {
        if(count%2!=0){
            return minq.peek()/1.0;
        }else{
            return (minq.peek()+maxq.peek())/2.0;
        }
    }


}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务