[leetcode]Merge Intervals
来源:互联网 发布:淘宝快速冲销量的方法 编辑:程序博客网 时间:2024/05/01 23:41
Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
解题思路:先将数组排序存入栈中,然后每次取出两个元素,判断第一个元素与第二个元素是否可以合并,如果不可以合并,则将第一个元素
入目标容器,然后将第二个元素赋值给第一个,如果可以合并,构造出合并后的新元素,再将新元素赋给第一个元素。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */class Solution {public: typedef struct mCompFunc{ bool operator()(Interval a, Interval b){ return a.start < b.start; } }mCompFunc; vector<Interval> merge(vector<Interval> &intervals) {vector<Interval> vi;stack<Interval> si;size_t n = intervals.size();if(n <= 1) return intervals;std::sort(intervals.begin(), intervals.end(), mCompFunc()); //将元素导入栈中for(int i = n - 1; i >= 0; i--){si.push(intervals[i]);}Interval a, b;a = si.top(); si.pop();while(!si.empty()){b = si.top(); si.pop();if(a.end < b.start){ //第一个元素与第二个元素不可以合并,将第一个存起来vi.push_back(a); a = b; //此时第一个指向第二个}else{ int end = b.end; //可以合并且判断最远的距离是一大还是二大 if(a.end > b.end){ end = a.end; } Interval tInterval(a.start, end);a = tInterval; //第一个元素指向合并后的元素}}vi.push_back(a); //将最后的一个入目标容器return vi; }};
0 0
- LeetCode: Merge Intervals
- LeetCode Merge Intervals
- LeetCode: Merge Intervals
- [Leetcode] Merge Intervals
- leetcode 28: Merge Intervals
- Leetcode: Merge Intervals
- [LeetCode] Merge Intervals
- [LeetCode]Merge Intervals
- leetcode merge intervals
- [leetcode]Merge Intervals
- LeetCode-Merge Intervals
- [leetcode] Merge Intervals
- LeetCode - Merge Intervals
- 【leetcode】Merge Intervals
- leetcode Merge Intervals
- LeetCode Merge Intervals
- [LeetCode] Merge Intervals
- LeetCode | Merge Intervals
- CCZone(...)
- Windows7 x64 + VMware + WinDbg 双机调试故障解决
- sql 关于文档的表中所有列、列的类型、列的说明、列字段等查询,表外键的查询
- java GridBagLayout 网格包布局管理器
- 用命令打开android应用
- [leetcode]Merge Intervals
- 【第二课】读取并显示图像
- CCString(内部std:string 实现。 成员:std::string变量 operator= intValue createWithFormat createWithContents)
- U-Boot启动过程--详细版的完全分析
- get mac of local net
- uva 147 Dollars 简单dp
- Hello,Wrold之环境搭建
- 未完待续02
- curl