Insert Interval
来源:互联网 发布:网络文明传播志愿小组 编辑:程序博客网 时间:2024/06/14 19:27
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).
Example
Insert [2, 5] into [[1,2], [5,9]], we get [[1,9]].
Insert [3, 4] into [[1,2], [5,9]], we get [[1,2], [3,4], [5,9]].
用merge interval的方法做比较简单,先添加进去,然后思路参考merge interval 那道题就可以了。
代码:
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> result = new ArrayList<Interval>(); if(intervals == null ) return result; intervals.add(newInterval); Collections.sort(intervals, new Comparator<Interval>(){ @Override public int compare(Interval o1, Interval o2){ return o1.start - o2.start; } }); for(int i=1;i<intervals.size();i++){ if(intervals.get(i).start<=intervals.get(i-1).end){ merge(intervals,i-1, i); i--; } } return intervals; } private void merge(List<Interval> intervals, int i, int j){ Interval i1 = intervals.get(i); Interval i2 = intervals.get(j); i1.end = Math.max(i1.end, i2.end); intervals.remove(j); }
0 0
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- cocos2dx使用通知节点NotificationNode的注意事项
- 一个小小99乘法表的思路
- Android内存优化之OOM
- Java操作HBase时报NotServingRegionException异常
- SIFT
- Insert Interval
- 微信小程序学习wx.request 中 post 出现500错误的一些成因
- 用反卷积(Deconvnet)可视化理解卷积神经网络
- VS2013修改 项目配置名称
- css圆角制作。
- C#debug跟踪C++DLL源码
- 事务的隔离级别
- UVA - 10602 Editor Nottoobad
- com.alibaba.fastjson.JSONException: default constructor not found