• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

Interval as an array:

 1 class Solution {
 2     public boolean canAttendMeetings(int[][] intervals) {
 3         if (intervals.length < 1) return true;
 4         
 5         Arrays.sort(intervals, (i1, i2) -> Integer.compare(i1[0], i2[0]));
 6         
 7         for (int i = 1; i < intervals.length; i ++) {
 8             if (intervals[i][0] < intervals[i - 1][1]) return false;
 9         }
10         return true;
11     }
12 }

 

Previous interval as an object:

Implement a Comparator<Interval>

Syntax: don't forget the public sign when defining a function

 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     public boolean canAttendMeetings(Interval[] intervals) {
12         if (intervals==null || intervals.length==0 || intervals.length==1) return true;
13         Comparator<Interval> comp = new Comparator<Interval>() {
14             public int compare(Interval i1, Interval i2) {
15                 return (i1.start==i2.start)? i1.end-i2.end : i1.start-i2.start;
16             }
17         };
18         
19         Arrays.sort(intervals, comp);
20         Interval pre = intervals[0];
21         for (int i=1; i<intervals.length; i++) {
22             Interval cur = intervals[i];
23             if (cur.start < pre.end) return false;
24             pre = cur;
25         }
26         return true;
27     }
28 }

 

posted @ 2015-12-22 08:32  neverlandly  阅读(302)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3