标签:
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; } }
标签:
原文地址:http://www.cnblogs.com/airwindow/p/4804112.html