Java TreeSet Custom Comparator


  • 0
    L
    public class SummaryRanges {
        TreeSet<Interval> set;
        List<Interval> cache;
        Comparator<Interval> sortInterval;
        Boolean dirty;
    
        public SummaryRanges() {
            sortInterval = new Comparator<Interval>(){
                @Override
                public int compare(Interval it1, Interval it2){
                    if(it1.start == it2.start) return 0;
                    if(it1.start < it2.start) return -1;
                    return 1;
                }
            };
            set = new TreeSet<Interval>(sortInterval);
            cache = new ArrayList<Interval>();
            dirty = false;
        }
        
        public void addNum(int val) {
            Interval itCur = new Interval(val, val);
            if(set.contains(itCur)) return;
            Interval itLower = set.lower(itCur), itHigher = set.higher(itCur);
            if(itLower != null && val <= itLower.end) return;
            if(itHigher != null && itHigher.start == val + 1 && itLower != null && val == itLower.end + 1){
                itLower.end = itHigher.end;
                set.remove(itHigher);
                dirty = true;
            }
            else if(itHigher != null && itHigher.start == val + 1 && (itLower == null || val > itLower.end + 1)){
                itHigher.start = val;
            }
            else if((itHigher == null || itHigher.start > val + 1) && itLower != null && val == itLower.end + 1){
                itLower.end = val;
            }
            else{
                set.add(new Interval(val, val));
                dirty = true;
            }
        }
        
        public List<Interval> getIntervals() {
            if(!dirty) return cache;
            dirty = false;
            return cache = new ArrayList(set);
        }
    }

Log in to reply
 

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