【leetcode】第56题 Merge Intervals 题目+解析+代码

【题目】

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].

【解析】

本题意思是要把给出的区间集合合并,输出合并后的区间集合。思路不难,主要是要先排序再判断。

【代码】

public List merge(List intervals) {
        int n = intervals.size();
        if(n<2) return intervals;
        LinkedList res = new LinkedList();
        Collections.sort(intervals,new Comparator(){
            public int compare(Interval o1, Interval o2){
                return o1.start-o2.start;
            }
        });
        int left = intervals.get(0).start;
        int right = intervals.get(0).end;
        int m = 0;
        for(int i = 1; i= left){
                if(intervals.get(i).end>right){
                     right = intervals.get(i).end;
                     m = i;
                }
                if(intervals.get(i).start


你可能感兴趣的:(leetcode)