meeting room I & II

时间:2022-10-18 04:10:55

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.

这题和求解有多少架飞机在空中一样。

 public class Solution {
public boolean canAttendMeetings(Interval[] intervals) {
List<TimePoint> list = new ArrayList<TimePoint>(); for (Interval interval : intervals) {
list.add(new TimePoint(interval.start, true));
list.add(new TimePoint(interval.end, false));
} Collections.sort(list, new Comparator<TimePoint>() {
public int compare(TimePoint t1, TimePoint t2) {
if (t1.time < t2.time) {
return -;
} else if (t1.time > t2.time) {
return ;
} else {
if (t1.isStart) {
return ;
} else {
return -;
}
}
}
});
int count = ;
for (TimePoint t : list) {
if (t.isStart) {
count++;
if (count == ) return false;
} else {
count--;
}
}
return true;
}
} class TimePoint {
int time;
boolean isStart; public TimePoint(int time, boolean isStart) {
this.time = time;
this.isStart = isStart;
}
}

网上看到一个更简单的方法:先sort intervals, 然后看俩个相邻的点是否有重合。

 public boolean canAttendMeetings(Interval[] intervals) {
Arrays.sort(intervals, new Comparator<Interval>(){
public int compare(Interval a, Interval b){
return a.start-b.start;
}
}); for(int i=; i<intervals.length-; i++){
if(intervals[i].end>intervals[i+].start){
return false;
}
}
return true;
}

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]],
return 2.

方法和第一种相似。

 public class Solution {
public int minMeetingRooms(Interval[] intervals) {
List<TimePoint> list = new ArrayList<TimePoint>(); for (Interval interval : intervals) {
list.add(new TimePoint(interval.start, true));
list.add(new TimePoint(interval.end, false));
} Collections.sort(list, (t1, t2) -> {
if (t1.time < t2.time) {
return -;
} else if (t1.time > t2.time) {
return ;
} else {
if (t1.isStart) {
return ;
} else {
return -;
}
}
}); int count = , max = ;
for (TimePoint t : list) {
if (t.isStart) {
count++;
max = Math.max(count, max);
} else {
count--;
}
}
return max;
}
} class TimePoint {
int time;
boolean isStart; public TimePoint(int time, boolean isStart) {
this.time = time;
this.isStart = isStart;
}
}

follow up: group all meetings by meeting rooms. 我的解法是对所有会议急于start排序,然后按顺序的分组搞定。