easy java solution, beats 99%


  • 0
    R
    public class Solution {
        public List<Interval> merge(List<Interval> intervals) {
            List<Interval> list = new ArrayList<>();
            for( Interval iter : intervals) {
                int i = 0, j = list.size() - 1;
                if(j == -1) {
                    list.add(iter);
                    continue;
                }
                while(i <= j && iter.start > list.get(i).end) i++;
                while(j >= 0 && iter.end < list.get(j).start) j--;
                if(i > j) {
                    list.add(i, iter);
                }else {
                    Interval left = list.get(i);
                    left.start = Math.min(left.start, iter.start);
                    left.end = Math.max(list.get(j).end, iter.end);
                    while(i < j) {
                        list.remove(i+1);
                        j--;
                    }
                }
            }
            return list;
        }
    }

Log in to reply
 

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