LeetCode 252. Meeting Rooms(會議室)

jmspan發表於2016-04-07

原題網址:https://leetcode.com/problems/meeting-rooms/

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.

思路:按照開始時間排序,排好序之後,檢查相鄰的時間段是否重疊,方法是看start是否在另一個時間段的start和end之間(因為

start已經排好序,所以只檢查這個條件就足夠了)

/**
 * 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>() {
           @Override
           public int compare(Interval i1, Interval i2) {
               return i1.start - i2.start;
           }
        });
        for(int i=0; i<intervals.length-1; i++) {
            if (intervals[i].start <= intervals[i+1].start && intervals[i+1].start < intervals[i].end) return false;
        }
        return true;
    }
}

方法二:利用start<end的特性,分別對start和end進行排序。

/**
 * 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) {
        int[] starts = new int[intervals.length];
        int[] ends = new int[intervals.length];
        for(int i=0; i<intervals.length; i++) {
            starts[i] = intervals[i].start;
            ends[i] = intervals[i].end;
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        for(int i=1; i<intervals.length; i++) {
            if (ends[i-1] > starts[i]) return false;
        }
        return true;
    }
}

相關文章