Java for LeetCode 056 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]
.
解题思路一:
用两个指针startIndex和endIndex来维护每次添加intervals的start和end的位置,然后分类讨论即可,JAVA实现如下:
public List<Interval> merge(List<Interval> intervals) { List<Interval> list = new ArrayList<Interval>(); if (intervals.size() == 0) return list; list.add(intervals.get(0)); for (int i = 1; i < intervals.size(); i++) { Interval temp = intervals.get(i); int startIndex = 0, endIndex = 0; for (int j = 0; j < list.size(); j++) { if (temp.start > list.get(j).end) { startIndex += 2; endIndex += 2; continue; } if (temp.end < list.get(j).start) break; if (temp.start >= list.get(j).start) startIndex++; if (temp.end > list.get(j).end) { endIndex += 2; continue; } if (temp.end >= list.get(j).start) endIndex++; break; } if(startIndex==endIndex&&startIndex%2==0) list.add(startIndex/2,new Interval(temp.start,temp.end)); else if(startIndex%2==0&&endIndex%2==0){ list.get(startIndex/2).start=temp.start; list.get(startIndex/2).end=temp.end; for(int k=1;k<endIndex/2-startIndex/2;k++) list.remove(startIndex/2+1); } else if(startIndex%2==0&&endIndex%2!=0){ list.get(startIndex/2).start=temp.start; list.get(startIndex/2).end=list.get(endIndex/2).end; for(int k=1;k<=endIndex/2-startIndex/2;k++) list.remove(startIndex/2+1); } else if(startIndex%2!=0&&endIndex%2==0){ list.get(startIndex/2).end=temp.end; for(int k=1;k<endIndex/2-startIndex/2;k++) list.remove(startIndex/2+1); } else if(startIndex%2!=0&&endIndex%2!=0){ list.get(startIndex/2).end=list.get(endIndex/2).end; for(int k=1;k<=endIndex/2-startIndex/2;k++) list.remove(startIndex/2+1); } } return list; }
解题思路二:
首先构造一个比较器,对interval按照start进行排序,然后进行遍历,在遍历过程中,如果结果集合为空或者当前interval
与结果集合中的最后一个interval
不重叠,那么就直接将当前interval
直接加入到结果集合中;如果发生了重叠,那么将结果集合的最后一个interval
的右端点改为当前interval
的右端点,JAVA实现如下:
public List<Interval> merge(List<Interval> intervals) { List<Interval> list = new ArrayList<Interval>(); Comparator<Interval> comparator = new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { if (o1.start == o2.start) return o1.end - o2.end; return o1.start - o2.start; } }; Collections.sort(intervals, comparator); for (Interval interval : intervals) if (list.size() == 0 || list.get(list.size() - 1).end < interval.start) list.add(new Interval(interval.start, interval.end)); else list.get(list.size() - 1).end = Math.max(interval.end, list.get(list.size() - 1).end); return list; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。