LeetCode57. 插入区间

和上一题好像没什么区别,所以直接略微修改,是我想的太肤浅了?

class Solution {

	public List insert(List intervals, Interval newInterval) {
		if (intervals == null)
			return new LinkedList<>();
		intervals.add(newInterval);
		Interval[] arr = new Interval[intervals.size()];
		for (int i = 0; i < arr.length; ++i) {
			arr[i] = intervals.get(i);
		}
		Arrays.sort(arr, new Comparator() {
			@Override
			public int compare(Interval o1, Interval o2) {
				return Integer.valueOf(o1.start).compareTo(o2.start);
			}
		});
		Deque queue = new ArrayDeque<>(arr.length);
		int i = 0;
		queue.addLast(arr[i++]);
		for (; i < arr.length; ++i) {
			Interval interval = queue.pollLast();
			// 可以合并
			if (arr[i].start <= interval.end && arr[i].start >= interval.start) {
				Interval newi = new Interval(interval.start, Math.max(interval.end, arr[i].end));
				queue.add(newi);
			} else {
				queue.add(interval);
				queue.add(arr[i]);
			}
		}
		List result = new LinkedList<>();
		while (!queue.isEmpty()) {
			result.add(queue.pop());
		}

		return result;
	}
}

你可能感兴趣的:(LeetCode57. 插入区间)