java solution, beats 100%


  • 0
    R
    /**
     * Definition for an interval.
     * public class Interval {
     *     int start;
     *     int end;
     *     Interval() { start = 0; end = 0; }
     *     Interval(int s, int e) { start = s; end = e; }
     * }
     */
    public class SummaryRanges {
        Set<Interval> set;
        /** Initialize your data structure here. */
        public SummaryRanges() {
            set = new TreeSet<>((Interval i1, Interval i2) -> i1.start - i2.start);
        }
        
        public void addNum(int val) {
            if(!contains(set, val)) {
                addNum(set, val);
            }
        }
        
        public List<Interval> getIntervals() {
            return new ArrayList<>(set);
        }
        /**
         * tools
         */
        private void addNum(Set<Interval> list, int val) {
            Interval left = null;
            Interval right = null;
            for(Interval iter : list) {
                if(iter.end == val - 1) left = iter;
                else if(iter.start == val + 1) right = iter;
            }
            if(left == null && right == null) list.add(new Interval(val, val));
            else if( left == null && right != null) right.start--;
            else if( left != null && right == null) left.end++;
            else {
                left.end = right.end;
                list.remove(right);
            }
        }
        
        
         private boolean contains(Set<Interval> list, int val) {
             if(list.isEmpty()) return false;
             for(Interval inter : list) {
                 if(inter.start <= val && inter.end >= val)
                 return true;
             }
             return false;
         }
        
        
    }
    
    /**
     * Your SummaryRanges object will be instantiated and called as such:
     * SummaryRanges obj = new SummaryRanges();
     * obj.addNum(val);
     * List<Interval> param_2 = obj.getIntervals();
     */
    

Log in to reply
 

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