本文主要是介绍56. Merge Interval,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
解答:
常规的合并,根据前后interval是否有交集判定。
代码:
/*** 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:static int compare(const Interval& A, const Interval& B){return A.start < B.start;}vector<Interval> merge(vector<Interval>& intervals) {sort(intervals.begin(), intervals.end(), compare);int len = intervals.size();if(len < 2) return intervals;vector<Interval> result;bool goend = false;for(int i = 0;i < len - 1; ++i){if(intervals[i].end < intervals[i+1].start){result.push_back(intervals[i]);}else{int index = i, right = intervals[index].end;while(index + 1 < len && right >= intervals[index+1].start){index++;if(intervals[index].end > right)right = intervals[index].end;}if(index + 1 == len)goend = true;Interval tmp(intervals[i].start, right);result.push_back(tmp);i = index;}}if(!goend)result.push_back(intervals[len-1]);return result;}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)
这篇关于56. Merge Interval的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!