标签:
Insert Interval
问题:
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
思路:
插入位置+merge
我的代码:
public class Solution { public List<Interval> merge(List<Interval> intervals) { if(intervals == null || intervals.size() == 0) return intervals; Collections.sort(intervals, new IntervalComparator()); for(int i = 0; i < intervals.size() - 1; i++) { Interval one = intervals.get(i); Interval two = intervals.get(i+1); if(one.end >= two.start) { one.end = Math.max(one.end, two.end); intervals.remove(i+1); i--; } } return intervals; } private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } } }
他人代码:
public class Solution { public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { if (newInterval == null || intervals == null) { return intervals; } ArrayList<Interval> results = new ArrayList<Interval>(); int insertPos = 0; for (Interval interval : intervals) { if (interval.end < newInterval.start) { results.add(interval); insertPos++; } else if (interval.start > newInterval.end) { results.add(interval); } else { newInterval.start = Math.min(interval.start, newInterval.start); newInterval.end = Math.max(interval.end, newInterval.end); } } results.add(insertPos, newInterval); return results; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4490116.html