252, 253. meeting room I & II
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.
这题和求解有多少架飞机在空中一样。
1 public class Solution { 2 public boolean canAttendMeetings(Interval[] intervals) { 3 List<TimePoint> list = new ArrayList<>(); 4 5 for (Interval interval : intervals) { 6 list.add(new TimePoint(interval.start, true)); 7 list.add(new TimePoint(interval.end, false)); 8 } 9 10 Collections.sort(list, (t1, t2) -> { 12 if (t1.time < t2.time) { 13 return -1; 14 } else if (t1.time > t2.time) { 15 return 1; 16 } else { 17 if (t1.isStart) { 18 return 1; 19 } else { 20 return -1; 21 } 22 } 23 } 24 }); 25 int count = 0; 26 for (TimePoint t : list) { 27 if (t.isStart) { 28 count++; 29 if (count == 2) return false; 30 } else { 31 count--; 32 } 33 } 34 return true; 35 } 36 } 37 38 class TimePoint { 39 int time; 40 boolean isStart; 41 42 public TimePoint(int time, boolean isStart) { 43 this.time = time; 44 this.isStart = isStart; 45 } 46 }
网上看到一个更简单的方法:先sort intervals, 然后看俩个相邻的点是否有重合。
1 public class Solution { 2 public boolean canAttendMeetings(Interval[] intervals) { 3 Arrays.sort(intervals, (a, b) -> a.start - b.start); 4 5 for (int i = 0; i < intervals.length - 1; i++) { 6 if (intervals[i].end > intervals[i + 1].start) { 7 return false; 8 } 9 } 10 return true; 11 } 12 }
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
.
方法和第一种相似。
1 public class Solution { 2 public int minMeetingRooms(Interval[] intervals) { 3 List<TimePoint> list = new ArrayList<TimePoint>(); 4 5 for (Interval interval : intervals) { 6 list.add(new TimePoint(interval.start, true)); 7 list.add(new TimePoint(interval.end, false)); 8 } 9 10 Collections.sort(list, (t1, t2) -> { 11 if (t1.time < t2.time) { 12 return -1; 13 } else if (t1.time > t2.time) { 14 return 1; 15 } else { 16 if (t1.isStart) { 17 return 1; 18 } else { 19 return -1; 20 } 21 } 22 }); 23 24 int count = 0, max = 0; 25 for (TimePoint t : list) { 26 if (t.isStart) { 27 count++; 28 max = Math.max(count, max); 29 } else { 30 count--; 31 } 32 } 33 return max; 34 } 35 } 36 37 class TimePoint { 38 int time; 39 boolean isStart; 40 41 public TimePoint(int time, boolean isStart) { 42 this.time = time; 43 this.isStart = isStart; 44 } 45 }
follow up: group all meetings by meeting rooms. 我的解法是对所有会议急于start排序,然后按顺序的分组搞定。