S*******e 发帖数: 379 | 1 想试一下insert interval的online judge,结果出现
Run Status: Runtime Error
没有具体的错误信息,这种情况是不是说明程序core dump了,而不是test case
failure? 好像没法debug啊。
程序在下面。
class Solution {
public:
vector insert(vector &intervals, Interval
newInterval) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int start, end;
vector::iterator it = intervals.begin();
while (newInterval.start > it->start && newInterval.start > it->end
&& it != intervals.end()) {
++ it;
}
if (newInterval.start < it->start || it == intervals.end()) { //
start from a point between two intervals
start = newInterval.start;
} else {
start = it->start;
}
while (newInterval.end > it->start && newInterval.end > it->end &&
it != intervals.end() ) {
it = intervals.erase(it);
}
if (newInterval.end < it->start || it == intervals.end()){ // end at
a point between two intervals
end = newInterval.end;
} else {
end = it->end;
it = intervals.erase(it);
}
Interval interval(start,end);
intervals.insert(it, interval);
}
}; |
i**********e 发帖数: 1145 | 2 你没考虑特殊状况,ie:
intervals.size() == 0
把你的
it != intervals.end()
状况移到第一个判定条件,short-circuit 就过了 :) |
S*******e 发帖数: 379 | 3 啊,确实犯了这个低级错误,多谢人工debug!
不过我把end() check 挪到了前面还是runtime error啊
改过的程序如下:
class Solution {
public:
vector insert(vector &intervals, Interval
newInterval) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int start, end;
vector::iterator it = intervals.begin();
while (it != intervals.end() && newInterval.start > it->start &&
newInterval.start > it->end) {
++ it;
}
if (it == intervals.end() || newInterval.start < it->start) { //
start from a point between two intervals
start = newInterval.start;
} else {
start = it->start;
}
while (it != intervals.end() && newInterval.end > it->start &&
newInterval.end > it->end ) {
it = intervals.erase(it);
}
if (it == intervals.end() || newInterval.end < it->start){ // end at
a point between two intervals
end = newInterval.end;
} else {
end = it->end;
it = intervals.erase(it);
}
Interval interval(start,end);
intervals.insert(it, interval);
}
};
【在 i**********e 的大作中提到】 : 你没考虑特殊状况,ie: : intervals.size() == 0 : 把你的 : it != intervals.end() : 状况移到第一个判定条件,short-circuit 就过了 :)
|
i**********e 发帖数: 1145 | 4 你少了一句:
return intervals :P |
S*******e 发帖数: 379 | 5 啊,还真是,多谢多谢!
一个小建议:这题interval 是pass by reference,不用再return了吧
【在 i**********e 的大作中提到】 : 你少了一句: : return intervals :P
|