lintcode(30)插入区间
来源:互联网 发布:电视连网络怎么看电视 编辑:程序博客网 时间:2024/06/05 22:58
/** * Definition of Interval: * public classs Interval { * int start, end; * Interval(int start, int end) { * this.start = start; * this.end = end; * } */class Solution { /** * Insert newInterval into intervals. * @param intervals: Sorted interval list. * @param newInterval: A new interval. * @return: A new sorted interval list. */ public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> result = new ArrayList<Interval>(); // write your code here if(intervals.size() == 0){ result.add(newInterval); return result; } Interval temp = newInterval; for(int i = 0;i<intervals.size();i++){ if(temp.end < intervals.get(i).start){ result.add(temp); for(int j = i;j<intervals.size();j++){ result.add(intervals.get(j)); } break; }else if(temp.start > intervals.get(i).end){ result.add(intervals.get(i)); }else{ temp.start = Math.min(temp.start , intervals.get(i).start); temp.end = Math.max(temp.end , intervals.get(i).end); } if(i == intervals.size()-1){ result.add(temp); } } return result; }}
问题描述 :
给出一个无重叠的按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
示例:插入区间[2, 5] 到 [[1,2], [5,9]],我们得到 [[1,9]]。
插入区间[3, 4] 到 [[1,2], [5,9]],我们得到 [[1,2], [3,4], [5,9]]。
理解:相当于若干个区间球并集,并且要注意各个区间没有重叠,也就是有重叠就要合并
解题思路:
如果新插入的区间和原来的集合没有并集,那么需要找到插入的位置,对每个区间进行比较,判断条件new.start>Integers[i].end && new.end<Integers[i+1].start
如果有并集,更新new,new.start = min(Integers[i].start , new.start),new.end = max(Integers[i].end , new.end)
代码:
0 0
- lintcode(30)插入区间
- LintCode 30 插入区间
- (lintcode)第30题 插入区间
- lintcode-插入区间
- 插入区间 lintcode
- LintCode 插入区间
- LintCode【插入区间】
- Lintcode 插入区间
- LintCode--插入区间
- LintCode 插入区间
- Lintcode:插入区间
- 【LintCode】Insert Intervals 插入区间
- LintCode-搜索区间
- lintcode-156-合并区间
- lintcode-搜索区间-61
- Lintcode搜索区间
- LintCode : 搜索区间
- LintCode:搜索区间
- 虚拟机中Centos7安装完毕后无法联网显示Server not found的解决方法
- h5移动端知识要点
- 安卓使用emoji表情
- Android---重新认识view--Visiable\Invisiable\Gone属性
- 根据body的内容 查找ul标签的@class="subtitle"的值
- lintcode(30)插入区间
- getSupportFragmentManager().findFragmentById()返回为null
- iOS基础动画
- button 按下改变颜色
- linux啟動openoffice
- Recycleview上拉隐藏与下拉显示
- 关于 Oracle客户端工具出现“ora-12705 Cannot access NLS data files or invalid environment specified”错误的解决办法
- 向量范数与矩阵范数
- Linux_Linux内存机制—Linux内存中的Cache真的能被回收么?