首页 > 代码库 > meeting room I & II
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<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, new Comparator<TimePoint>() { 11 public int compare(TimePoint t1, TimePoint 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 boolean canAttendMeetings(Interval[] intervals) { 2 Arrays.sort(intervals, new Comparator<Interval>(){ 3 public int compare(Interval a, Interval b){ 4 return a.start-b.start; 5 } 6 }); 7 8 for(int i=0; i<intervals.length-1; i++){ 9 if(intervals[i].end>intervals[i+1].start){ 10 return false; 11 } 12 } 13 return true; 14 }
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, new Comparator<TimePoint>() { 11 public int compare(TimePoint t1, TimePoint 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 int max = 0; 27 for (TimePoint t : list) { 28 if (t.isStart) { 29 count++; 30 max = Math.max(count, max); 31 } else { 32 count--; 33 } 34 } 35 return max; 36 } 37 } 38 39 class TimePoint { 40 int time; 41 boolean isStart; 42 43 public TimePoint(int time, boolean isStart) { 44 this.time = time; 45 this.isStart = isStart; 46 } 47 }
meeting room I & II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。