您的位置:首页 > 其它

【Leetcode】Merge Intervals

2016-06-03 10:11 211 查看
题目链接: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]
.

思路:

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

算法:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: