leetcode有时候会要求一些奇怪(陌生)的数据形式,刷题因为数据形式卡住了真的很不好...
合并区间里定义了一个Interval的结构数组
struct Interval { int start; int end; Interval() : start(), end() {} Interval(int s, int e) : start(s), end(e) {} };
又根据结构数组创建了vector<Interval> intervals。我就在想,怎么初始化这个intervals。
vector<Interval> intervals; Interval int1(,); intervals.push_back(int1); Interval int2(,); intervals.push_back(int2);
其实就是利用结构数组里的定义来,这样初始化真的很方便呐,也不用去特意申请空间。
解题思路:
先根据start排序,再一一合并
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <vector> using namespace std; typedef struct Interval Int; struct Interval { int start; int end; Interval() : start(), end() {} Interval(int s, int e) : start(s), end(e) {} }; class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { int n = intervals.size(); ) return intervals; int j; Interval temp; Interval temp0; ; ;i<n;i++){ temp = intervals[i]; && temp.start<intervals[j-].start;j--){ intervals[j].start = intervals[j-].start; intervals[j].end = intervals[j-].end; } intervals[j].start = temp.start; intervals[j].end = temp.end; } vector<Interval> outcome; outcome.push_back(intervals[]); ;i<n;i++){ if(intervals[i].start <= outcome.back().end){ outcome.back().end = outcome.back().end > intervals[i].end ? outcome.back().end:intervals[i].end; } else{ outcome.push_back(intervals[i]); } } return outcome; } }; int main(){ vector<Interval> intervals; Interval int1(,); intervals.push_back(int1); Interval int2(,); intervals.push_back(int2); // Interval int3(8,10); intervals.push_back(int3); // Interval int4(15,18); intervals.push_back(int4); Solution S; vector<Interval> outCome = S.merge(intervals); ;i<outCome.size();i++){ int1 = outCome[i]; printf("%d %d\n", int1.start, int1.end); } ; }