合并间隔
来源:互联网 发布:微信淘宝优惠卷公众号 编辑:程序博客网 时间:2024/06/12 00:49
问题:
给一组间隔,把这些间隔合并,使得间隔之间不会有重合。比如:[1, 5], [3, 8], [10, 20], [7, 9] 合并后变成 [1, 9], [10, 20]。
分析:
首先,因为我们需要判断是否两个间隔是否重合,这样才能合并,检查两个间隔是否重合的代码是:
/* * s1: start point of interval 1 * e1: end point of interval 1 * s2: start point of interval 2 * e2: end point of interval 2 */public boolean overlap(int s1, int e1, int s2, int e2) {return Math.max(s1, s2) < Math.min(e1, e2);}然后,我们把间隔按照开始值排序,这样,从头开始检查,如果当前间隔和前一个间隔重合,就合并。否则,直接把它加入到list里面。
代码如下:
public class Test {//check whether the two intervals intersectpublic boolean overlap(Interval i1, Interval i2) {return Math.max(i1.start, i2.start) < Math.min(i1.end, i2.end);}//merge the intervals and return a new interval list without overlappingpublic void merge(ArrayList<Interval> list) {int currentPosition = 0;for (int i = 1; i < list.size(); i++) {//no intersectionif (overlap(list.get(i), list.get(currentPosition)) == false) {currentPosition++;} else {//get the new intervalint start = Math.min(list.get(i).start, list.get(currentPosition).start);int end = Math.max(list.get(i).end, list.get(currentPosition).end);Interval interval = new Interval(start, end);list.remove(currentPosition);list.add(currentPosition, interval);}}int size = list.size();for (int i = currentPosition + 1; i < size; i++) {list.remove(currentPosition + 1);}}public static void main(String[] args) {ArrayList<Interval> list = new ArrayList<Interval>();list.add(new Interval(3, 8));list.add(new Interval(2, 29));list.add(new Interval(5, 17));list.add(new Interval(22, 47));list.add(new Interval(32, 48));Collections.sort(list);new Test().merge(list);for(Interval inter : list) {System.out.println("[" + inter.start + ", " + inter.end + "]");}}}class Interval implements Comparable<Interval>{int start;int end;Interval(int start, int end) {this.start = start;this.end = end;}public int compareTo(Interval o) {if (start > ((Interval)o).start || (start == ((Interval)o).start && end > ((Interval)o).end)) {return 1;} else if (start == ((Interval)o).start && end == ((Interval)o).end) {return 0;}return -1;}}转载请注明出处:http://blog.csdn.net/beiyeqingteng
- 合并间隔
- 56.合并间隔
- Java Merge Intervals(合并间隔)
- ftiasch 两个字符串间隔合并
- LeetCode | Merge Intervals(合并区间间隔)
- 每天一道LeetCode-----将间隔集中有重叠的间隔合并
- 间隔
- Leetcode #56. Merge Intervals 间隔合并 解题报告
- 给定一组不重叠的间隔,在间隔中插入一个新的间隔(如有必要,合并)。间隔最初按照起始时间进行排序。
- 把数组中前后两段合并,后段的数间隔插在前段中。空间复杂度O(1)
- 间隔年
- 间隔分区
- 时间间隔
- 时间间隔
- 时间间隔
- 最大间隔
- 时间间隔
- 最大间隔
- 根据文件头来判断图片的类型
- Go语言开发工具 LiteIDE x12 发布
- android的selector,背景选择器的使用
- 并口、串口区别
- 255. Learn not and know not. 不学无术
- 合并间隔
- .NET设计模式合集
- 使用Log时需要做和避免做的事情
- XmlSerializer 常见问题
- 苹果面试8大难题及答案
- SecureCRT中解决SQLPLUS上下左右键问题
- sqlite3使用简介
- 线程优先级关联性
- 权限管理之共享主键