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".

  • 相关阅读:
    C#多线程编程之:集合类中Synchronized方法与SyncRoot属性原理分析
    Newtonsoft.Json 序列化和反序列化 以及时间格式 2 高级使用
    C++:基类和派生类
    C++:友元(非成员友元函数、成员友元函数、友元类)
    C++:静态成员
    C++:向函数传递对象(对象、对象指针、对象引用)
    C++:常类型Const
    C++:对象的赋值和复制
    C++:类的组合
    C++:析构函数
  • 原文地址:https://www.cnblogs.com/prmlab/p/6950218.html
Copyright © 2011-2022 走看看