Description

Given an array of meeting time intervals where intervals[i] = [start_i, end_i], determine if a person could attend all meetings.


給定一個會議時間的陣列 intervals,其中 intervals[i] = [start_i, end_i],判斷一個人是否能參加所有會議。


Example 1

Input: intervals = [[0,30],[5,10],[15,20]]
Output: false

Example 2

Input: intervals = [[7,10],[2,4]]
Output: true

Constraints:

Solution

function canAttendAllMeetings(intervals:number[][]) :boolean{
	// 先排序開始的時間
	intervals.sort((a,b) => a[0] - b[0])
	
	// 上一個會議結束的時間
	let prevEnd = 0 
	
	for(const [start, end] of intervals){
		// 看會議開始時間 有沒有比上一個會議結束的時間還早
		if (start < prevEnd) {
      return false
    }
    // 更新最新會議結束時間
    prevEnd = Math.max(prevEnd, end)
	}
	
	return true
}

// Example usage
const intervals1 = [[0, 30], [5, 10], [15, 20]];
const canAttend1 = canAttendAllMeetings(intervals1);
console.log("Intervals 1:", canAttend1); // Output: false

const intervals2 = [[7, 10], [2, 4]];
const canAttend2 = canAttendAllMeetings(intervals2);
console.log("Intervals 2:", canAttend2); // Output: true

Complexity