I have recently come across a confusing situation. I don't know the explanation. Here is my simple code:
class Solution {
public:
bool canAttendMeetings(vector<Interval>& intervals) {
sort(intervals.begin(), intervals.end(), compare);
for (int i=0; i<intervals.size()-1; i++) {
if (intervals[i].end > intervals[i+1].start) return false;
}
return true;
}
private:
static bool compare(const Interval &interval1, const Interval &interval2) {
return interval1.start < interval2.start;
}
};
The problem is at this line:
for (int i=0; i<intervals.size()-1; i++) {
I got the runtime error for the input: []. However, I figured out the fix and it's pretty simple but hard to explain. Here is the fix, I just assign intervals.size() to a new variable before the for loop.
class Solution {
public:
bool canAttendMeetings(vector<Interval>& intervals) {
sort(intervals.begin(), intervals.end(), compare);
int n = intervals.size();
for (int i=0; i<n-1; i++) {
if (intervals[i].end > intervals[i+1].start) return false;
}
return true;
}
private:
static bool compare(const Interval &interval1, const Interval &interval2) {
return interval1.start < interval2.start;
}
};
Can anyone explain to me why the first version doesn't work but the second version works? Thanks a lot!
The problem is that size()
returns an unsigned 0 when the container is empty.
You either want to convert that to a signed zero before subtracting one (as your working code did) or put more thought into how empty should behave. Such as:
for (std:size_t i=1; i<intervals.size(); i++) {
if (intervals[i-1].end > intervals[i].start) return false;
The above assumes you knew that subtracting one from an unsigned zero gives you a very big number, rather than a negative number (and you just didn't realize your code was subtracting one from an unsigned zero). But in case you thought subtracting one from an unsigned zero gave a negative result, now you know.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.