LintCode【插入区间】
来源:互联网 发布:mac下mysql客户端 编辑:程序博客网 时间:2024/05/18 00:58
给出一个无重叠的按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
样例
插入区间[2, 5] 到 [[1,2], [5,9]],我们得到 [[1,9]]。
插入区间[3, 4] 到 [[1,2], [5,9]],我们得到 [[1,2], [3,4], [5,9]]。
/** * 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>(); //如果带插入的区间为空,则返回插入区间 if(intervals.isEmpty()){ result.add(newInterval); return result; } int pos =0; //遍历循环list for(int i=0;i<intervals.size();i++){ Interval cur = intervals.get(i); if(cur.end<newInterval.start){//如果插入的新区间比当前区间要大,那么先add当前区间到result中,并将标记位后移一位 result.add(cur); pos++; }else if(cur.start>newInterval.end){//相反地,直接将当前区间add到result中 result.add(cur); }else{ newInterval.start = Math.min(cur.start,newInterval.start); newInterval.end = Math.max(cur.end,newInterval.end); } } //利用add方法在指定的pos插入newInterval result.add(pos,newInterval); return result; }}
总结
这种类型的题目可以自己拿出笔多画一画看看到底有多少种情况
0 0
- lintcode-插入区间
- 插入区间 lintcode
- LintCode 插入区间
- LintCode【插入区间】
- lintcode(30)插入区间
- LintCode 30 插入区间
- Lintcode 插入区间
- LintCode--插入区间
- LintCode 插入区间
- Lintcode:插入区间
- 【LintCode】Insert Intervals 插入区间
- (lintcode)第30题 插入区间
- LintCode-搜索区间
- lintcode-156-合并区间
- lintcode-搜索区间-61
- Lintcode搜索区间
- LintCode : 搜索区间
- LintCode:搜索区间
- H5手机移动端WEB开发资源整合 常用的标签及注意事项
- linux环境下ipython notebook安装GraphLab
- JAVA 例子--输入三个整数,按由小到大的顺序进行排序
- 温度可调上下限,1602显示
- 10012---quartz--quartz简介,下载和核心接口
- LintCode【插入区间】
- Oracle建立database links
- Volley用法解析二(转载自郭霖郭大神的CSDN博客)
- JSP、Servlet与JavaBean实现从表单传输到数据库验证完成登录功能
- Dropout资源【1】
- Unit6 运算符与表达式
- HDU2553 N皇后
- [LeetCode] Container With Most Water 解题报告
- 多线程编程(1)