LeetCode OJ 57 Insert Interval [hard]

来源:互联网 发布:淘宝买家信誉快速 编辑:程序博客网 时间:2024/05/28 23:20

题目描述:

Given a set of non-overlappingintervals, insert a new interval into the intervals (merge if necessary).

You may assume thatthe intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9], insertand merge [2,5] in as [1,5],[6,9].

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].

This is because thenew interval [4,9] overlaps with [3,5],[6,7],[8,10].

理解:

给定一个区间组成的集合,插入衣蛾新的区间到集合中,合并需要合并的区间

This is because thenew interval [4,9] overlaps with [3,5],[6,7],[8,10].

分析:

将新的区间加入到区间集合中,再升序排序,按照题目56的方法进行合并;

解答:

public static class Interval {    int start;    int end;    Interval() {        start = 0;        end = 0;    }    Interval(int s, int e) {        start = s;        end = e;    }}public static List<Interval> insert(List<Interval> intervals, Interval newInterval) {    List<Interval> ans = new ArrayList<>();    intervals.add(newInterval);    Collections.sort(intervals, new Comparator<Interval>() {        @Override        public int compare(Interval o1, Interval o2) {            return Integer.compare(o1.start, o2.start);        }    });    int start = intervals.get(0).start;    int end = intervals.get(0).end;    for (int i = 1; i < intervals.size(); i++) {        if (end >= intervals.get(i).start) {            end = Math.max(end, intervals.get(i).end);        } else {            ans.add(new Interval(start, end));            start = intervals.get(i).start;            end = intervals.get(i).end;        }    }    ans.add(new Interval(start, end));    return ans;}


 

原创粉丝点击