LeetCode 252. Meeting Rooms (会议室)$

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.

 


 

题目标签:sort

  这道题目给了我们一个array的会议时间,让我们判断是否能够参加所有的会议。每一个会议时间都有start 和 end。只要把array 重新排序一下,按照start从小到大。之后遍历每一个会议时间,如果这个会议时间的end 大于 下一个会议时间的start,就判断false。

起初自己写了一个n^n 的sort,通过后发现速度贼慢,只好重新研究其他人的做法。可以利用Arrays.sort 来直接sort我们的intervals, 但是需要结合comparator。之前都有用Arrays.sort, 但是对于这样的object array就没想到,而且也不会用comparator。顺便稍微调查了一下,Arrays.sort 是用两种排序方法, 1- 快速排序, 2-优化的合并排序。 快速排序主要运用于基本类型(int, short...), 合并排序用于对象类型。两种排序都是O(n logn)。对于object的Arrays.sort,需要override一个compare function, a - b就是ascending排序,从小到大; b - a 就是descending排序。

 

Java Solution:

Runtime beats 75.89% 

完成日期:06/24/2017

关键词:Sort

关键点:如何用Arrays.sort 和 Comparator

 


 

 

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() { start = 0; end = 0; }
 7  *     Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 public class Solution 
11 {
12     public boolean canAttendMeetings(Interval[] intervals) 
13     {
14         // step 1: sort the intervals
15         Arrays.sort(intervals, new Comparator<Interval>(){
16             public int compare(Interval a, Interval b)
17             {
18                 return a.start - b.start;
19             }
20         });
21         
22         // step 2: iterate intervals to check each end is <= next start
23         for(int i=0; i<intervals.length-1; i++)
24         {
25             if(i+1 <intervals.length)
26             {
27                 if(intervals[i].start == intervals[i+1].start)
28                     return false;
29                 if(intervals[i].end > intervals[i+1].start)
30                     return false;
31             }
32         }
33         
34         return true;
35     }
36 }

 

参考资料: 

* http://www.programcreek.com/2014/07/leetcode-meeting-rooms-java/
* http://blog.csdn.net/lian47810925/article/details/4689323
* http://www.importnew.com/8952.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

posted @ 2017-06-25 04:47  Jimmy_Cheng  阅读(862)  评论(0编辑  收藏  举报