码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode#252] Meeting Rooms

时间:2015-09-13 10:28:33      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

[LeetCode#252] Meeting Rooms

标签:

原文地址:http://www.cnblogs.com/airwindow/p/4804112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!