Leetcode -- Merge Intervals

来源:互联网 发布:js 将图片转为base64 编辑:程序博客网 时间:2024/05/21 14:51

https://oj.leetcode.com/problems/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<Interval> merge(List<Interval> intervals)


分析:这一题要分两步。第一步是排序,根据interval的左值排序。

第二步才是合并。首先我们需要维护一个用来判断是否合并或者直接插入的变量interval X,合并的步骤分两种情况讨论,第一种情况是合并,其实就是X的右值大于等于当前遍历到的interval的左值,这个时候更新X的右值如果当前遍历到的interval的右值大于X的右值。第二种情况则是插入,也就是X的右值小于当前遍历到的interval,这个时候就是不存在overlap了,那么就将X插入新的结果数组,然后当前的Interval就成为新的X进行之后的操作。给出代码如下:

    public List<Interval> merge(List<Interval> intervals) {        Collections.sort(intervals, new IntervalComparator());        List<Interval> res = new LinkedList<Interval>();        if(intervals.size() == 0)            return res;        int curstart = intervals.get(0).start;        int curend = intervals.get(0).end;        for(int i = 1; i < intervals.size(); i++){            Interval tmp = intervals.get(i);            if(tmp.start > curend){                res.add(new Interval(curstart, curend));                curstart = tmp.start;                curend = tmp.end;            }else{                curend = Math.max(tmp.end, curend);            }        }        res.add(new Interval(curstart, curend));        return res;    }        public class IntervalComparator implements Comparator<Interval>{        @Override        public int compare(Interval a, Interval b){            return (new Integer(a.start)).compareTo(new Integer(b.start));        }    }


0 0
原创粉丝点击