LintCode--插入区间
来源:互联网 发布:关闭淘宝手机验证 编辑:程序博客网 时间:2024/06/08 10:30
题目描述:
给出一个无重叠的按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
样例:
插入区间[2, 5] 到 [[1,2], [5,9]],我们得到 [[1,9]]。
插入区间[3, 4] 到 [[1,2], [5,9]],我们得到 [[1,2], [3,4], [5,9]]。
解题思路:
我们将有序排列的区间放置在数轴上可以表示为:
图中红色的竖线表示为起始区间(上区间),蓝色为结束区间(下区间),则从左向右依次为:上、上、下、上、下、下。如果将刚才的次序依次存入栈中,且定义当元素为“上”时,入栈当前下标,若为“下”时,进行弹栈操作,如果栈为空,则可以确定一个区间,直到蓝色的竖线遍历完为止。所以步骤如下:
- 申请一个用于存储“上”区间的数组和“下”区间的数组
- 遍历原有序区间序列以及待插入区间使得整体为有序序列如上例
上区间为:[1,2,5]
下区间为:[2,5,9] 利用栈来对上区间和下区间进行入栈和弹栈操作,当栈为空时,说明得到了一个区间且区间的起始位置就是stack[0]的值 ,终点位置就是下区间使得弹栈栈为空的值, 并保存到result结果集中。
代码如下:
/** * Definition of Interval: * public classs Interval { * int start, end; * Interval(int start, int end) { * this.start = start; * this.end = end; * } */ public static ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { // write your code here ArrayList<Interval> result =new ArrayList<>(); //为上区间和下区间申请空间 int shangbiao[] = new int [intervals.size()+1]; int xiabiao[]= new int[intervals.size()+1]; int t1 = 0; int t2 = 0; //这里的flag只说明新的区间只能被利用一次,防止下面的for循环中判断有误,导致上下区间一直赋值新的区间的值 boolean flag1 = true; boolean flag2 = true; for (int i = 0; i < intervals.size(); ) { if(intervals.get(i).start>newInterval.start&&flag1) { shangbiao[t1++] = newInterval.start; flag1 = false; }else { shangbiao[t1++]=intervals.get(i++).start; } } for (int i = 0; i < intervals.size(); ) { if(intervals.get(i).end>newInterval.end&&flag2) { xiabiao[t2++] = newInterval.end; flag2 = false; }else { xiabiao[t2++]=intervals.get(i++).end; } } if(flag1) shangbiao[shangbiao.length-1]=newInterval.start;//如果flag没有被改成false说明新的区间的值是最大的 if(flag2) xiabiao[xiabiao.length-1]=newInterval.end; //打印结果检验上下区间的值是否为有序序列 for (int i : shangbiao) { System.out.print(i+" "); } System.out.println(""); for (int i : xiabiao) { System.out.print(i+" "); } //定义栈结构 int stack[] = new int[10000]; int top = -1; int i =0,j=0; stack[++top] = shangbiao[i++];//初始化 while(j<xiabiao.length) { if(i<shangbiao.length&&shangbiao[i]<=xiabiao[j]) { stack[++top] = shangbiao[i++]; }else { top--; j++; if(top==-1) //栈为空时,说明有一个区间 { result.add(new Interval(stack[0], xiabiao[j-1])); } } } 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:搜索区间
- java.lang.VerifyError: Verifier rejected class bad method
- 5、Spring技术栈-客户端、服务端数据验证
- LeetCode 617. Merge Two Binary Trees
- Hadoop关键技术理解
- HTTP状态码
- LintCode--插入区间
- vue---watch实战
- python 两个列表合并
- 顺序表基本运算算法
- HIVE 概述
- 背包dp之多重背包
- iOS addChildViewController方法
- 阿里云clouder认证—云数据库管理与数据迁移(实战篇)
- UML2.0