Share my simple Java solution, beat 99%


  • 0
    T

    Share my ArrayList solution here. Although I think the best way to solve this is through using a BST. However, the ArrayList version is much easier to write.

    public class SummaryRanges {
        private ArrayList<Interval> intervals;
        /** Initialize your data structure here. */
        public SummaryRanges() {
            this.intervals = new ArrayList<>();
        }
        
        public void addNum(int val) {
            Interval tmp = new Interval(val, val);
            int p = Collections.binarySearch(intervals, tmp, new Comparator<Interval>(){
                @Override
                public int compare(Interval a, Interval b) {
                    if (a.start < b.start) {
                        return -1;
                    } else if (a.start == b.start) {
                        return 0;
                    } else {
                        return 1;
                    }
                }
            });
            if (p >= 0) {
                return;
            }
            p = -p - 1;
            
            if (p > 0 && intervals.get(p-1).end >= val) {
                return;
            } else if (p > 0 && p < intervals.size() && intervals.get(p-1).end == val-1 && intervals.get(p).start == val+1) {
                intervals.get(p-1).end = intervals.get(p).end;
                intervals.remove(p);
            } else if (p > 0 && intervals.get(p-1).end == val-1) {
                intervals.get(p-1).end = val;
            } else if (p < intervals.size() && intervals.get(p).start == val+1) {
                intervals.get(p).start = val;
            } else {
                intervals.add(p, tmp);
            }
            
        }
        
        public List<Interval> getIntervals() {
            return intervals;
        }
    }
    

Log in to reply
 

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