leetcode:使用STL:基于红黑树的TreeSet
2016-11-15 14:26
295 查看
352. 数据流的不相交区间
给定一个数据流,输入一组非负整数a1, a2, …, an, …, 对截止到当前的不相交区间进行汇总。思路:
利用TreeSet数据结构,将不相交区间Interval存储在TreeSet中。TreeSet底层使用红黑树实现,可以用log(n)的代价实现元素查找。每次执行addNum操作时,利用TreeSet找出插入元素val的左近邻元素floor(start值不大于val的最大Interval),以及右近邻元素higher(start值严格大于val的最小Interval),然后根据floor, val, higher之间的关系决定是否对三者进行合并。
/** * Definition for an interval. * public class Interval { * int start; * int end; * Interval() { start = 0; end = 0; } * Interval(int s, int e) { start = s; end = e; } * } */ public class SummaryRanges { /** Initialize your data structure here. */ private TreeSet<Interval> intervalSet; public SummaryRanges() { intervalSet = new TreeSet<Interval>(new Comparator<Interval>() { public int compare(Interval a, Interval b) { return a.start - b.start; } }); } public void addNum(int val) { Interval valInterval = new Interval(val, val); Interval floor = intervalSet.floor(valInterval); if (floor != null) { if (floor.end >= val) { return; } else if (floor.end + 1 == val) { valInterval.start = floor.start; intervalSet.remove(floor); } } Interval higher = intervalSet.higher(valInterval); if (higher != null && higher.start == val + 1) { valInterval.end = higher.end; intervalSet.remove(higher); } intervalSet.add(valInterval); } public List<Interval> getIntervals() { return Arrays.asList(intervalSet.toArray(new Interval[0])); } } /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges obj = new SummaryRanges(); * obj.addNum(val); * List<Interval> param_2 = obj.getIntervals(); */
相关文章推荐
- Largest Number|leetcode,使用stl sort函数排序,排序后容器的内容被改变,尝试各种办法没有找出bug,奇葩!!!!
- leetcode-Contains Duplicate,STL unique,unique_copy等函数的使用
- [LeetCode]LRUcache题解(不使用STL容器)
- 【C++ STL应用与实现】26: 如何使用std::for_each以及基于范围的for循环 (since C++11)
- 如何使用 c++ stl 中的 map 以及红黑树 (一)
- Java 基于红黑树的TreeMap,TreeSet实现原理
- 基于STL关联式容器的红黑树效果测试程序
- leetcode-27. Remove Element--STL Vector remove()和erase()的使用
- 使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- 关于最近使用stl的一些感受
- 如何在VC6中使用SGI-STL
- 使用索引的误区之三:基于函数的索引
- C#中使用XML——基于DOM的案例分析
- STL的心得(2)--如何使用安装STLPort
- 使用 Authorization Manager 对多层应用程序进行基于角色的访问控制
- 基于webform中使用水晶报表的现实问题(转摘)&showtopic=14318&st=0&#entry81715
- [导入]如何使用 C# .NET 在 ASP.NET 应用程序中实现基于窗体的身份验证
- 如何使用基于接口的Remote Objects的配置文件
- CUJ:高效使用标准库:STL中的unary predicate
- 基于asp.net的web页面动态控件创建以及使用