[leetcode-56]Merge Intervals(java)

问题描述:
Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

分析:思路是比较简单的,就是先排序,然后从前向后比较,是否存在相交的,如果存在,就合并,然后删除一个元素。依次下去,然后返回intervals。虽然AC了,但是绝对还是太慢了,猜想原因出在了频繁删除的部分。更改代码如代码2.
代码2是维护一个res队列,然后每次是比较res队列的顶部与intervals的当前元素。这样就没有了删除元素的麻烦。

代码如下:528ms

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
       public List merge(List intervals) {
         if(intervals.size()<=0)
            return intervals;
        //根据interval的start排序
        Collections.sort(intervals, new Comparator() {
            @Override
            public int compare(Interval o1, Interval o2) {
                if(o1.startreturn -1;
                else if(o1.start>o2.start)
                    return 1;
                else
                    return 0;
            }
        });

        for(int i = 0;i+11);
            if(current.end>=next.start){
                current.end = Math.max(current.end,next.end);
                intervals.remove(i+1);
                i--;
            }
        }

        return intervals;
    }
}

代码2:420ms

/**
 * Definition for an interval.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
       public List merge(List intervals) {
         List res = new LinkedList<>();
         if(intervals.size()<=0)
            return intervals;
        //根据interval的start排序
        Collections.sort(intervals, new Comparator() {
            @Override
            public int compare(Interval o1, Interval o2) {
                if(o1.startreturn -1;
                else if(o1.start>o2.start)
                    return 1;
                else
                    return 0;
            }
        });
        Interval top = intervals.get(0);
        res.add(new Interval(top.start,top.end));

        for(int i = 1;i1);

            if(top.end>=current.start){
                top.end = Math.max(current.end,top.end);
            }else
                res.add(new Interval(current.start,current.end));
        }

        return res;
    }
}

你可能感兴趣的:(leetcode)