leetcode--Merge Intervals
来源:互联网 发布:中华网络一条龙官方 编辑:程序博客网 时间:2024/06/06 02:29
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:根据题意,最简单的解法就是遍历,然后比较前一个集合的end,和下一个集合的start,如果start<end,那么合并这两个集合。
题目中的集合是没有顺序的,所以要先对他们按照start的大小从小到大排序,这个在java里面很好实现。
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */public class Solution { public List<Interval> merge(List<Interval> intervals) { List<Interval> res= new ArrayList<Interval>(); if(intervals.size()==0) return res; Collections.sort(intervals, new Comparator<Interval>() {//按照start排序 @Override public int compare(Interval interval1, Interval interval2) { return interval1.start - interval2.start; } }); int start = intervals.get(0).start; int end = intervals.get(0).end; int len = intervals.size(); for(int i=0;i<len;i++){//遍历 Interval cur = intervals.get(i); if(cur.start<=end){//如果需要合并,注意更新end end = cur.end>end?cur.end:end; }else{//如果不能合并,将当前合并结束的集合加入res,重新设置start和end res.add(new Interval(start,end)); start = cur.start; end = cur.end; } } res.add(new Interval(start,end)); return res; }}
0 0
- LeetCode: Merge Intervals
- LeetCode Merge Intervals
- LeetCode: Merge Intervals
- [Leetcode] Merge Intervals
- leetcode 28: Merge Intervals
- Leetcode: Merge Intervals
- [LeetCode] Merge Intervals
- [LeetCode]Merge Intervals
- leetcode merge intervals
- [leetcode]Merge Intervals
- LeetCode-Merge Intervals
- [leetcode] Merge Intervals
- LeetCode - Merge Intervals
- 【leetcode】Merge Intervals
- leetcode Merge Intervals
- LeetCode Merge Intervals
- [LeetCode] Merge Intervals
- LeetCode | Merge Intervals
- iOS APP提交流程
- JSP四大作用域
- 几个数组问题,持续更新
- C语言中的switch语句
- java__io__字符流
- leetcode--Merge Intervals
- MySQL学习1_Win7下安装MySQL5.6.26
- ZOJ 3362--Beer Problem【最大费用最大流 && 有值得注意的地方】
- HDOJ 4965 Fast Matrix Calculation
- C/C++堆栈详解
- C#中使用强制类型实现字符串和ASCII码之间的转换
- Tomcat虚拟目录配置和测试
- SQLAlchemy (三)---使用操作连接符
- 适配Tips