zoukankan      html  css  js  c++  java
  • [LeetCode#252] Meeting Rooms

    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;
        }
    }
  • 相关阅读:
    os.path.basename()和os.path.splitext()
    关于pytorch中@和*的用处
    Python | os.path.join() method
    SURF (Speeded Up Robust Features,加速稳健特征)
    Canny算子
    医学影像中常见名词解释
    sigmod、tanh、ReLU激活函数的实现
    plt.gca()坐标轴移动
    损失函数和梯度下降解释
    torch和numpy的相互转换
  • 原文地址:https://www.cnblogs.com/airwindow/p/4804112.html
Copyright © 2011-2022 走看看