码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Merge Intervals

时间:2016-06-03 11:23:33      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/merge-intervals/

题目:

Given a collection of intervals, merge all overlapping intervals.

For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].

思路:

  1. 将区间按左端点大小进行排序
  2. 将list转化为链表,便于动态删除合并区间
  3. 遍历链表,将遍历结果返回

算法:

	class LinkedNode {
		Interval val;
		LinkedNode next;

		public LinkedNode(Interval val, LinkedNode next) {
			this.val = val;
			this.next = next;
		}
	}

	public List<Interval> merge(List<Interval> intervals) {
		List<Interval> res = new ArrayList<Interval>();

		if (intervals == null || intervals.size() == 0)
			return res;
		// 按照区间的起点进行排序
		Collections.sort(intervals, new Comparator<Interval>() {
			public int compare(Interval o1, Interval o2) {
				if (o1.start > o2.start) {
					return 1;
				} else if (o1.start < o2.start) {
					return -1;
				} else {
					return 0;
				}
			}
		});

		// 改为链表结构
		Interval headv = new Interval(0, 0);
		LinkedNode head = new LinkedNode(headv, null);
		LinkedNode p = head;
		for (Interval v : intervals) {
			LinkedNode node = new LinkedNode(v, null);
			p.next = node;
			p = node;
		}
		// 检查、合并

		LinkedNode v1, v2;
		v1 = head.next;

		while (v1.next != null) {
			v2 = v1.next;
			if (v1.val.end >= v2.val.start) {// 交叉
				if (v1.val.end >= v2.val.end) {// v1包含v2
					v1.next = v2.next;
				} else {// 非包含的交叉
					v1.next = v2.next;
					v1.val.end = v2.val.end;
				}
			} else {
				v1 = v1.next;
			}
		}

		p = head.next;
		while (p != null) {
			res.add(p.val);
			p = p.next;
		}
		return res;
	}


【Leetcode】Merge Intervals

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51576739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!