[leetcode] 252. Meeting Rooms 解題報告

小榕流光發表於2016-02-26

題目連結: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排個序,然後檢視是否每個會議的的開始時間都比前一個結束時間大.

程式碼如下:

/**
 * 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) {
        auto cmp = [](Interval a, Interval b) { return a.start < b.start; };
        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;
    }
};

python

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution(object):
    def canAttendMeetings(self, v):
        """
        :type intervals: List[Interval]
        :rtype: bool
        """
        v.sort(key = lambda val: val.start)
        return not any(v[i].start < v[i-1].end for i in range(1,len(v)))
        



相關文章