[LintCode/LeetCode] Meeting Rooms

linspiration發表於2019-01-19

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.

Example

Given intervals = [[0,30],[5,10],[15,20]], return false.

Note

兩次迴圈遍歷

Solution

public class Solution {
    /**
     * @param intervals: an array of meeting time intervals
     * @return: if a person could attend all meetings
     */
    public boolean canAttendMeetings(List<Interval> intervals) {
        // Write your code here
        int size = intervals.size();
        for (int i = 0; i < size-1; i++) {
            Interval a = intervals.get(i);
            for (int j = i+1; j < size; j++) {
                Interval b = intervals.get(j);
                if ((a.start > b.start && a.start < b.end) || 
                    (b.start > a.start && b.start < a.end)) {
                    return false;
                }
            }
        }
        return true;
    }
}

Update 2018-10

class Solution {
    public boolean canAttendMeetings(Interval[] intervals) {
        if (intervals == null || intervals.length < 2) return true;
        List<Interval> list = Arrays.asList(intervals);
        Collections.sort(list, (a, b)->a.start-b.start);
        Interval pre = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i).start < pre.end) return false;
            else pre = list.get(i);
        }
        return true;
    }
}

相關文章