[LeetCode#252] Meeting Rooms
2015-09-13 10:11
148 查看
Problem:
Given an array of meeting time intervals consisting of start and end times
For example,
Given
return
Analysis:
Solution:
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.
Analysis:
The problem is very easy!!! But I have made a mistake in defining comparator. Comparator<Interval> interval_sort = new Comparator<Interval>() { @Override public int compare(Interval interval_1, Interval interval_2) { if (interval_1.start < interval_2.start) return interval_1.start - interval_2.start; return interval_1.end - interval_2.end; } }; Error case: Runtime Error Message: Line 53: java.lang.IllegalArgumentException: Comparison method violates its general contract! This is a logic error for the above code. suppose we have interval_1 and interval_2. iff interval_1.start < interval_2.start, we would return return interval_1.start - interval_2.start; <a negative number> The error part is at otherwise. What if we swap the reference of them, can we still get the same answer? Iff "interval_1.start > interval_2.start" ? Then we use the end for the comparision!!!! Why don't just use start!!!! Wrong ! Right! If you indeed want take the end into consideration. You should use "==", which would not break the comparision's logic. if (interval_1.start == interval_2.start) return return interval_1.end - interval_2.end; return interval_1.start - interval_2.start;
Solution:
public class Solution { public boolean canAttendMeetings(Interval[] intervals) { if (intervals == null) throw new IllegalArgumentException("intervals is null"); int len = intervals.length; if (len <= 1) return true; Comparator<Interval> interval_sort = new Comparator<Interval>() { @Override public int compare(Interval interval_1, Interval interval_2) { return interval_1.start - interval_2.start; } }; Arrays.sort(intervals, interval_sort); for (int i = 1; i < len; i++) { if (intervals[i-1].end > intervals[i].start) return false; } return true; } }
相关文章推荐
- PS CS6中如何制作简易GIF动画图片
- linux 安装flash
- Eclipse关联java源代码
- 孙正义鲜为人知的早期创业史
- poj2594:Treasure Exploration
- POJ 2686 Traveling by Stagecoach
- 斯坦福Developing iOS 8 Apps学习笔记(四)
- 前端框架
- 【JSP】JSP中9个内置对象
- android:src
- 处理运行时状态的改变
- “米粉节”背后的故事——小米网抢购系统开发实践
- [leetcode] Rotate Array
- CGI、FastCGI、PHP-CGI、PHP-FPM、Spawn-FCGI?
- leetcode之路034 Search for a Range
- ffmpeg配置
- Raft一致性算法
- iredmail centos下简要安装指南
- Unity3D笔记第十天——刚体及物理材质
- sizeof()数组名和指针的结果