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 had made a mistake in defining Comparator.comparator<Interval> Interval_sort =NewComparator<interval>() {@Override Public intCompare (Interval interval_1, Interval interval_2) {if(Interval_1.start <Interval_2.start)returnInterval_1.start-Interval_2.start; returnInterval_1.end-Interval_2.end; }}; Error Case: Runtime Error message:line53:java.lang.illegalargumentexception:comparison method violates its general contract!This is a logic error forThe above code.suppose we have Interval_1 and interval_2. IFF Interval_1.start< Interval_2.start, we wouldreturnreturnInterval_1.start-interval_2.start; <a Negative number>The error is at otherwise. whatifWe swap the reference of them, can we still get the same answer?Iff"Interval_1.start > Interval_2.start"?Then we use the end forTHE comparision!!!! Why don ' t just use start!!!! Wrong! right!If You indeed want take the end into consideration. Should use"= =", which would not BreakThe comparision ' s logic.if(Interval_1.start = =Interval_2.start)return returnInterval_1.end-Interval_2.end;returnInterval_1.start-interval_2.start;
Solution:
Public classSolution { Public Booleancanattendmeetings (interval[] intervals) {if(Intervals = =NULL) Throw NewIllegalArgumentException ("Intervals is null"); intLen =intervals.length; if(Len <= 1) return true; Comparator<Interval> Interval_sort =NewComparator<interval>() {@Override Public intCompare (Interval interval_1, Interval interval_2) {returnInterval_1.start-Interval_2.start; } }; Arrays.sort (intervals, interval_sort); for(inti = 1; i < Len; i++) { if(Intervals[i-1].end >Intervals[i].start)return false; } return true; }}
[leetcode#252] Meeting Rooms