您的位置:首页 > 其它

[LeetCode#252] Meeting Rooms

2015-09-13 10:11 148 查看
Problem:

Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...]
(si < ei), determine if a person could attend all meetings.

For example,
Given
[[0, 30],[5, 10],[15, 20]]
,
return
false
.

Analysis:

The problem is very easy!!!
But I have made a mistake in defining comparator.
Comparator<Interval> interval_sort = new Comparator<Interval>() {
@Override
public int compare(Interval interval_1, Interval interval_2) {
if (interval_1.start < interval_2.start)
return interval_1.start - interval_2.start;
return interval_1.end - interval_2.end;
}
};

Error case:
Runtime Error Message:
Line 53: java.lang.IllegalArgumentException: Comparison method violates its general contract!

This is a logic error for the above code.
suppose we have interval_1 and interval_2.
iff interval_1.start < interval_2.start, we would return
return interval_1.start - interval_2.start; <a negative number>

The error part is at otherwise.
What if we swap the reference of them, can we still get the same answer?
Iff "interval_1.start > interval_2.start" ?
Then we use the end for the comparision!!!! Why don't just use start!!!! Wrong ! Right!

If you indeed want take the end into consideration. You should use "==", which would not break the comparision's logic.
if (interval_1.start == interval_2.start)
return return interval_1.end - interval_2.end;
return interval_1.start - interval_2.start;


Solution:

public class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
if (intervals == null)
throw new IllegalArgumentException("intervals is null");
int len = intervals.length;
if (len <= 1)
return true;
Comparator<Interval> interval_sort = new Comparator<Interval>() {
@Override
public int compare(Interval interval_1, Interval interval_2) {
return interval_1.start - interval_2.start;
}
};
Arrays.sort(intervals, interval_sort);
for (int i = 1; i < len; i++) {
if (intervals[i-1].end > intervals[i].start)
return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: