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.

分析:

题目只要求判断是否能参加meeting所以只是考一个重载运算符的sort。如果是考虑具体时间,找能参加的最多会议,则成为一道典型贪心法?

这道题目重载comparator的做法注意两点,

(1) compare可以是任意函数只要结果能转化为bool

(2) compare必须是static function如果定义在类下,而又不使用类的成员。

解法:

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    static bool compare(const Interval& left, const Interval& right) {
        return left.start < right.start;
    }

    bool canAttendMeetings(vector<Interval>& intervals) {
        if (intervals.size() == 0) {
            return true;
        }
        sort(intervals.begin(), intervals.end(), compare);
        for(int i = 0; i < intervals.size() - 1; i++) {
            if (intervals[i].end > intervals[i + 1].start) {
                return false;
            }
        }
        return true;
    }
};

results matching ""

    No results matching ""