昨晚做了一道LeetCode算法题,Merge Intervals,题目难度中等,原题链接: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]
.
大意为:给定一组区间,把有重叠部分的区间合并,返回;
思路是先按照interval.start将区间排序,然后判断interval[i].end>=interval[i+1]?如果满足条件,则合并两个区间,否则不处理,时间复杂度为排序的复杂度nlgn;
代码如下:
class Solution {
public:
static bool compare(const Interval& a, const Interval& b) {
return a.start < b.start;
}
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if (intervals.empty())
return result;
sort(intervals.begin(), intervals.end(), compare);
result.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i].start <=result.back().end) {
result.back().end = max(result.back().end, intervals[i].end);
}
else
result.push_back(intervals[i]);
}
return result;
}
};
现在有两个问题想问问大家,第一个问题如下:
compare函数为什么一定要为声明为静态类型呢????
第二个问题:
int main() {
ifstream infile;
infile.open("test.txt");
string s;
if (!infile) {
cout << "open error" << endl;
exit(1);
}
vector<Interval>test;
int Int=0;
int Int1=0, Int2=0;
int i = 0;
//infile >> Int;
while (!infile.eof())
{
//infile >> Int;
if ((i % 2) == 0)
//Int1 = Int;
infile >> Int1;
else
{
//Int2 = Int;
infile>>Int2;
Interval interval(Int1,Int2);
test.push_back(interval);
}
i++;
}
Solution solution;
vector<Interval>result = solution.merge(test);
for (int i = 0; i < result.size(); i++) {
cout << result[i].start << " " << result[i].end << endl;
}
return 0;
}
第一次在vs上写代码,上述代码在Ubuntu上跑没问题,为啥在vs2015上会在再while条件下进入死循环???
不懂,test.txt文件中数据:
1,2,3,4,3,4,2,5,7,8,9,10