252. 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]],
returnfalse.

S: sort O(nlogn)

对interval按起始时间排序,再判断前后两个interval起始终止时间是否重叠

/**
 * 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:
    bool canAttendMeetings(vector<Interval>& intervals) {
        sort(intervals.begin(), intervals.end(), cmp);
        for (int i = 1; i < intervals.size(); ++i) {
            if (intervals[i].start < intervals[i-1].end) {
                return false;
            }
        }
        return true;
    }

private:
    static bool cmp(Interval a, Interval b) {
        return a.start < b.start;
    }
};

253. Meeting Rooms II

Given an array of meeting time intervals consisting of start and end times[[s1,e1],[s2,e2],...](si< ei), find the minimum number of conference rooms required.

For example,
Given[[0, 30],[5, 10],[15, 20]],
return2.

S: sweep line O(nlogn)

拆分区间排序

/**
 * 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:
    int minMeetingRooms(vector<Interval>& intervals) {
        vector<timeNode> nodes;
        for (Interval i : intervals) {
           timeNode startNode(i.start, true);
           timeNode endNode(i.end, false);
           nodes.push_back(startNode);
           nodes.push_back(endNode);
        }
        sort(nodes.begin(), nodes.end());
        int maxRoom = 0;
        int curRoom = 0;
        for (const auto& i : nodes) {
            if (i.isStart) {
                curRoom++;
                maxRoom = max(maxRoom, curRoom);
            } else {
                curRoom--;
            }
        }
        return maxRoom;
    }

private:
    struct timeNode {
        int time;
        bool isStart;
        timeNode(int x, bool y): time(x), isStart(y) {}
        bool operator < (cosnt timeNode& a) const {
            if (time == a.time) {
                return !isStart;
            }
            return time < a.time;
        }
    };
};

results matching ""

    No results matching ""