Very simple Java solution using Iterator and Lambda Expression


  • 0
    B
    public List<Interval> merge(List<Interval> intervals) {
            List<Interval> res = new ArrayList<Interval>();
            if (intervals.size() == 0) return res;
            Collections.sort(intervals,(i1, i2) -> i1.start - i2.start);
            Iterator<Interval> iter = intervals.iterator();
            Interval cur = iter.next();
            while (iter.hasNext()) {
                Interval next = iter.next();
                if (cur.end >= next.start) {
                    if (cur.end < next.end) {
                        cur.end = next.end;
                    }
                } else {
                    res.add(cur);
                    cur = next;
                }
            }
            res.add(cur);
            return res;
        }
    

Log in to reply
 

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