首页 > 其他 > 详细

LeetCode | Insert Interval

时间:2014-03-23 09:43:25      阅读:303      评论:0      收藏:0      [点我收藏+]

题目

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.

Example 1:
Given intervals [1,3],[6,9], insert and 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 the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

分析

从头到尾来一遍,O(n)的复杂度。

看到网上还有其他比较凶残的O(lgn)的方法,没有细看了。Java版本用的是ArrayList,不管啥方法,为了得到最终答案,移动数组的平均时间复杂度都要O(n)了。

代码

import java.util.ArrayList;

public class InsertInterval {
	public ArrayList<Interval> insert(ArrayList<Interval> intervals,
			Interval newInterval) {
		ArrayList<Interval> result = new ArrayList<Interval>();
		int N = intervals.size();
		for (int i = 0; i < N; ++i) {
			Interval interval = intervals.get(i);
			if (interval.start > newInterval.end) {
				result.add(newInterval);
				for (int j = i; j < N; ++j) {
					result.add(intervals.get(j));
				}
				return result;
			} else if (interval.end < newInterval.start) {
				result.add(interval);
			} else {
				newInterval.start = Math.min(newInterval.start, interval.start);
				newInterval.end = Math.max(newInterval.end, interval.end);
			}
		}
		result.add(newInterval);
		return result;
	}
}

LeetCode | Insert Interval,布布扣,bubuko.com

LeetCode | Insert Interval

原文:http://blog.csdn.net/perfect8886/article/details/21780789

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!