Leetcode 252 meeting rooms

来源:互联网 发布:c语言编译器有啥用 编辑:程序博客网 时间:2024/04/28 20:30


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.


/** * Definition for an interval. * public class Interval { *     int start; *     int end; *     Interval() { start = 0; end = 0; } *     Interval(int s, int e) { start = s; end = e; } * } */public class Solution {    public boolean canAttendMeetings(Interval[] intervals) {        Arrays.sort( intervals,            new Comparator<Interval> () {                public int compare(Interval itv1, Interval itv2) {                    return itv1.start - itv2.start;                }            }                    );                for (int i = 1; i < intervals.length; i++) {            if (intervals[i].start < intervals[i-1].end) {                return false;            }        }        return true;    }}



Best answer:
private boolean canAttendMeetings(Interval[] intervals) {    try {        Arrays.sort(intervals, new IntervalComparator());    } catch (Exception e) {        return false;    }    return true;}private class IntervalComparator implements Comparator<Interval> {    @Override    public int compare(Interval o1, Interval o2) {        if (o1.start < o2.start && o1.end <= o2.start)            return -1;        else if (o1.start > o2.start && o1.start >= o2.end)            return 1;        throw new RuntimeException();    }}





0 0
原创粉丝点击