Java 10line one TreeSet AC


  • 0
    Y
    class MedianFinder {
        private TreeSet<Double> tset=new TreeSet<>();
        private int n=0;
        private double mid=0,base=0.00001;
        /** initialize your data structure here. */
        public MedianFinder() {
        }
        
        public void addNum(int num) {
            double newNum=(double)num+base*n;
            tset.add(newNum);
            if(n==0) mid=newNum;
            else if(n%2==1){
                if(newNum<mid) mid=tset.lower(mid);
            } 
            else if(newNum>mid) mid=tset.higher(mid);
            n++;
        }
        
        public double findMedian() {
            return (n%2==1)?(double)(Math.round(mid)):(double)(Math.round(tset.higher(mid)+mid))/2.0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.