Insert Interval

Given a non-overlapping interval list which is sorted by start point.

Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

Example

Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].

Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].


用merge interval的方法做比较简单,先添加进去,然后思路参考merge interval 那道题就可以了。

代码:

public ArrayList insert(ArrayList intervals, Interval newInterval) {
        ArrayList result = new ArrayList();

        if(intervals == null ) return result;
        
        intervals.add(newInterval);
        
        Collections.sort(intervals, new Comparator(){
            @Override 
            public int compare(Interval o1, Interval o2){
                return o1.start - o2.start;
            }
        });
        
        
        for(int i=1;i intervals, int i, int j){
        Interval i1 = intervals.get(i);
        Interval i2 = intervals.get(j);
        i1.end = Math.max(i1.end, i2.end);
        intervals.remove(j);
    }


你可能感兴趣的:(算法,leetcode)