zoukankan      html  css  js  c++  java
  • 252. Meeting Rooms

    https://leetcode.com/problems/meeting-rooms/#/description

    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.

    Sol:

    The end time of the previous interval should be less or equal than the start time of the start time of the next interval....But wait, sort out first! by ascending order of the start time. 

    # Definition for an interval.
    class Interval(object):
        def __init__(self, s=0, e=0):
            self.start = s
            self.end = e
    
    class Solution(object):
        def canAttendMeetings(self, intervals):
            """
            :type intervals: List[Interval]
            :rtype: bool
            """
            if len(intervals) < 2:
                return True
            intervals = sorted(intervals, key = lambda x: x.start)
            for i in range(len(intervals)-1):
                if intervals[i].end > intervals[i+1].start:
                    return False
            return True
            
            

    Note:

    1 The input list is composed of tuples. 

    ex. s = [ [11,22], [33, 44] ]

    len(s) = 2

    2 The problem pre-defines the class of the tuple object.  Tuples are [s, e] and they are defined as:

    self.start = s

    self.end = e

    So when calling the first element of the tuple, we should use intervals.start.  

    3 Edge Check! 

    4 One way to sort by certain element of a turple. 

    intervals = sorted(intervals, key = lambda x: x.start)

    1) sorted, key = lambda are the build-in python chars. x can be any name.

    2) The sentence above means sort intervals by the start/first element.

    3)Two more examples:

    ex1.

    s = [['b', 2], ['a', 1], ['c', 0]]

    s = sorted(s, key = lambda any_name: any_name[0])

    print s

    ==>  [['a', 1], ['b', 2], ['c', 0]]

    This is sorted by the first element of the tuple. 

    ex2. 

    s = [['b', 2], ['a', 1], ['c', 0]]

    s = sorted(s, key = lambda any_name: any_name[1])

    print s

    ==>  [['c', 0], ['a', 1], ['b', 2]]

    This is sorted by the second element of the tuple. 

     5 Pay attention to the end condition of the index in for loop, especially the loop contains index + 1 or index - 1.  Otherwise it will get  "Line 17: IndexError: list index out of range".

  • 相关阅读:
    JavaScript中严格模式"use strict";需注意的几个雷区:
    React 学习,需要注意几点
    安装了VS2012 还有Update4 我的Silverlight5安装完后 我的Silverlight4项目打不开
    SilverLight抛出 System.InvalidOperationException: 超出了2083 的最大URI
    Dictionary集合运用
    配置OpenCV开发环境心得
    调用第三方库出现的问题
    7-19 答疑课小结
    工欲善其事必先利其器(篇一)
    VMware Ubuntu Kaldi
  • 原文地址:https://www.cnblogs.com/prmlab/p/6950218.html
Copyright © 2011-2022 走看看