252. Meeting Rooms
Array, Sorting, AMateList ·Problem Statement
link: LeetCode.cn LeetCode Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints: 0 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti < endi <= 106
Solution Approach
The solution involves sorting the intervals by their start times and then checking if any meeting overlaps by comparing the end time of the current meeting with the start time of the next meeting.
Algorithm
- Sort the Intervals: Start by sorting the list of intervals based on their start times to ensure the meetings are in chronological order.
- Check for Overlaps: Iterate through the sorted intervals, comparing the end time of each meeting with the start time of the next. If any end time exceeds the next start time, a conflict is detected.
- Return the Result: If no overlaps are found during the iteration, return True, indicating that all meetings can be attended. Otherwise, return False if any overlap is detected.
Implement
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
ins = sorted(intervals)
n = len(intervals)
for i in range(n - 1):
if ins[i][1] > ins[i + 1][0]:
return False
return True