Accepted Java Solution using lambda and Iterator


  • 0
    B
    class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            if(intervals == null || intervals.size() <=1)
            {
                return intervals;
            }
            
            intervals.sort(
                (p1, p2) -> {
                                if(p1.start != p2.start)
                                {
                                    // 
                                    // https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#compare-int-int-
                                    //
                                     return Integer.compare(p1.start, p2.start);
                                }
                                else
                                {
                                    return Integer.compare(p1.end, p2.end);
                                }
                            }
            );
            // 
            // by using iterator, we could remove the interval after merge
            //
            ListIterator<Interval> it = intervals.listIterator();
            
            Interval cur = it.next();
            
            while(it.hasNext())
            {
                Interval next = it.next();
                //
                // if there is no overlap, move on
                //
                if(cur.end < next.start)
                {
                    cur = next;
                    continue;
                }
                else
                {
                    //
                    //  if overlapped, merge the two intervals,
                    //  remove the current merged interval
                    //
                    cur.end = Math.max(cur.end, next.end);
                    it.remove();
                }
            }
            
            return intervals;
        }
    }
    

Log in to reply
 

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