Insert Interval

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;
        }
    }
}
View Code

他人代码:

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;
    }
}
View Code

学习之处:

  • 我的代码需要进行两遍的扫描,别人代码需要一遍扫描,我的空间复杂度是O(1),别人的代码空间复杂度是O(n)

posted on 2015-05-09 15:03  zhouzhou0615  阅读(136)  评论(0编辑  收藏  举报

导航