Merge Intervals--LeetCode

昨晚做了一道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


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值