leetcode:Merge Intervals(合并相交集合) 【面试算法题】
2013-09-25 18:49
399 查看
题目:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
题意把相交的集合合并。
按start排序,遍历的时候判断前后集合是否有相交,如果没有就把之前的集合输出。
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].
题意把相交的集合合并。
按start排序,遍历的时候判断前后集合是否有相交,如果没有就把之前的集合输出。
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ bool cmp(Interval a,Interval b) { return a.start<b.start; } class Solution { public: vector<Interval> merge(vector<Interval> &intervals) { vector<Interval> result; sort(intervals.begin(),intervals.end(),cmp); int i,j,left=-1,right=-1,len=intervals.size(); for(i=0;i<len;++i) { if(intervals[i].start<=right) { right=max(right,intervals[i].end); } else { if(left!=-1)result.push_back(Interval(left,right)); left=intervals[i].start; right=intervals[i].end; } } if(left!=-1)result.push_back(Interval(left,right)); return result; } };
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【056-Merge Intervals(区间合并)】
- 【LeetCode-面试算法经典-Java实现】【056-Merge Intervals(区间合并)】
- 【LeetCode-面试算法经典-Java实现】【021-Merge Two Sorted Lists(合并两个排好序的单链表)】
- 【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】
- 【LeetCode-面试算法经典-Java实现】【088-Merge Sorted Array(合并排序数组)】
- leetcode:Merge Sorted Array(合并两个有序数组到其中一个数组中)【面试算法题】
- 【LeetCode-面试算法经典-Java实现】【116-Populating Next Right Pointers in Each Node(二叉树链接右指针)】
- 【LeetCode-面试算法经典-Java实现】【118-Pascal's Triangle(帕斯卡三角形)】
- leetcode:Plus One (加一)【面试算法题】
- leetcode:Populating Next Right Pointers in Each Node II (顺序连接二叉树每一层节点)【面试算法题】
- leetcode:Remove Element (删除给定元素)【面试算法题】
- 【LeetCode-面试算法经典-Java实现】【136-Single Number(只出现一次的数字)】
- LeetCode 问题难度,面试出现频率及问题相关数据结构和算法
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】
- [LeetCode] Merge Intervals 合并区间
- LeetCode 问题难度,面试出现频率及问题相关数据结构和算法
- 【LeetCode-面试算法经典-Java实现】【081-Search in Rotated Sorted Array II(搜索旋转的排序数组)】
- leetcode:Multiply Strings(字符串的乘法)【面试算法题】
- 【LeetCode-面试算法经典-Java实现】【217-Contains Duplicate(包含重复元素)】
- leetcode:N-Queens (n皇后问题) 【面试算法题】