数组
排序
题目描述
给定一个会议时间安排的数组 intervals
,每个会议时间都会包括开始和结束的时间 intervals[i] = [starti , endi ]
,请你判断一个人是否能够参加这里面的全部会议。
示例 1:
输入: intervals = [[0,30],[5,10],[15,20]]
输出 :false
示例 2:
输入: intervals = [[7,10],[2,4]]
输出 :true
提示:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti < endi <= 106
解法
方法一:排序
我们将会议按照开始时间进行排序,然后遍历排序后的会议,如果当前会议的开始时间小于前一个会议的结束时间,则说明两个会议有重叠,返回 false
即可。
遍历结束后,返回 true
。
时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 $n$ 为会议数量。
Python3 Java C++ Go TypeScript Rust
class Solution :
def canAttendMeetings ( self , intervals : List [ List [ int ]]) -> bool :
intervals . sort ()
return all ( a [ 1 ] <= b [ 0 ] for a , b in pairwise ( intervals ))
1
2
3
4
5
6
7
8
9
10
11
12
13 class Solution {
public boolean canAttendMeetings ( int [][] intervals ) {
Arrays . sort ( intervals , ( a , b ) -> a [ 0 ] - b [ 0 ] );
for ( int i = 1 ; i < intervals . length ; ++ i ) {
var a = intervals [ i - 1 ] ;
var b = intervals [ i ] ;
if ( a [ 1 ] > b [ 0 ] ) {
return false ;
}
}
return true ;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14 class Solution {
public :
bool canAttendMeetings ( vector < vector < int >>& intervals ) {
sort ( intervals . begin (), intervals . end (), []( const vector < int >& a , const vector < int >& b ) {
return a [ 0 ] < b [ 0 ];
});
for ( int i = 1 ; i < intervals . size (); ++ i ) {
if ( intervals [ i ][ 0 ] < intervals [ i - 1 ][ 1 ]) {
return false ;
}
}
return true ;
}
};
func canAttendMeetings ( intervals [][] int ) bool {
sort . Slice ( intervals , func ( i , j int ) bool {
return intervals [ i ][ 0 ] < intervals [ j ][ 0 ]
})
for i := 1 ; i < len ( intervals ); i ++ {
if intervals [ i ][ 0 ] < intervals [ i - 1 ][ 1 ] {
return false
}
}
return true
}
function canAttendMeetings ( intervals : number [][]) : boolean {
intervals . sort (( a , b ) => a [ 0 ] - b [ 0 ]);
for ( let i = 1 ; i < intervals . length ; ++ i ) {
if ( intervals [ i ][ 0 ] < intervals [ i - 1 ][ 1 ]) {
return false ;
}
}
return true ;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 impl Solution {
#[allow(dead_code)]
pub fn can_attend_meetings ( intervals : Vec < Vec < i32 >> ) -> bool {
if intervals . len () == 1 {
return true ;
}
let mut intervals = intervals ;
// Sort the intervals vector
intervals . sort_by ( | lhs , rhs | lhs [ 0 ]. cmp ( & rhs [ 0 ]));
let mut end = - 1 ;
// Begin traverse
for p in & intervals {
if end == - 1 {
// This is the first pair
end = p [ 1 ];
continue ;
}
if p [ 0 ] < end {
return false ;
}
end = p [ 1 ];
}
true
}
}