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一下,然后看前一个时间段的末尾数字是不是大于后一个时间段的开头数字就好。
l.sort()
for i in range(len(l) - 1):
if l[i][1] > l[i+1][0]:
return False
return True
然而因为数据结构是如下
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
所以并不能那样直接用sort方法。用python的话,能直接在sort方法中加入一个匿名方法用于排序。
intervals.sort(key = lambda x:(x.start, x.end))
所以sort了之后还是能直接继续对比判断,得到结果。
class Solution(object):
def canAttendMeetings(self, intervals):
intervals.sort(key = lambda x:(x.start, x.end))
for i in range(len(intervals) - 1):
if intervals[i].end > intervals[i+1].start:
return False
return True
80ms。
=======================
O(n*n) Bubble sort 有些test case会超时,但不否认是一个简单想到的方法。
class Solution(object):
def canAttendMeetings(self, intervals):
"""
:type intervals: List[Interval]
:rtype: bool
"""
for j in range(len(intervals)):
for i in range(len(intervals) - 1):
if intervals[i].start > intervals[i+1].start:
intervals[i], intervals[i+1] = intervals[i+1], intervals[i]
for i in range(len(intervals) - 1):
if intervals[i].end > intervals[i+1].start:
return intervals
return True
尝试下O(nlogn)的Merge sort
class Solution(object):
def canAttendMeetings(self, intervals):
intervals = self.msort(intervals)
for i in range(len(intervals) - 1):
if intervals[i].end > intervals[i+1].start:
return False
return True
def msort(self, x):
result = []
if len(x) < 2:
return x
mid = int(len(x)/2)
y = self.msort(x[:mid])
z = self.msort(x[mid:])
i = 0
j = 0
while i < len(y) and j < len(z):
if y[i].start > z[j].start:
result.append(z[j])
j += 1
else:
result.append(y[i])
i += 1
result += y[i:]
result += z[j:]
return result
从来没有注意过,python自带的sort()方法要比merge sort还要快的多。虽然通过了test case,但是100ms+。仅供参考。