Skip to content

Commit e8ca0c1

Browse files
author
Chris Wu
committed
no message
1 parent 430b509 commit e8ca0c1

File tree

3 files changed

+52
-5
lines changed

3 files changed

+52
-5
lines changed

problems/meeting-rooms-ii.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,13 @@ def minMeetingRooms(self, intervals):
2929

3030
return result
3131

32-
# Definition for an interval.
33-
# class Interval(object):
34-
# def __init__(self, s=0, e=0):
35-
# self.start = s
36-
# self.end = e
32+
33+
34+
# Definition for an interval.
35+
# class Interval(object):
36+
# def __init__(self, s=0, e=0):
37+
# self.start = s
38+
# self.end = e
3739

3840
class Solution(object):
3941
def minMeetingRooms(self, intervals):

problems/meeting-rooms.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
Time: O(NLogN)
3+
Space: O(1)
4+
5+
Sort the interval (mainly by start time), see if the end overlaps with the start of next.
6+
"""
7+
class Solution(object):
8+
def canAttendMeetings(self, intervals):
9+
intervals.sort()
10+
11+
for i in xrange(len(intervals)-1):
12+
end = intervals[i][1]
13+
nextStart = intervals[i+1][0]
14+
if end>nextStart: return False
15+
16+
return True

problems/top-k-frequent-elements.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,33 @@ def topKFrequent(self, nums, k):
5959
return opt
6060

6161

62+
"""
63+
Time: O(N+KLogN).
64+
Building numToCounts takes O(N).
65+
Building heap takes O(N) (Yeah, I know. Some People thinks `heapify` takes O(NLogN) but it actually takes O(N). But that is another story...).
66+
HeapPop takes O(LogN).
67+
68+
Space: O(N)
69+
70+
1. Form `[(-count1, num1), (-count2, num2)]`, in this case `h`.
71+
Use "-count" its because heapq in python is min heap, so using negative value will make it pop out the most freq count.
6272
73+
2. Turn h into heap. (heapify)
74+
75+
3. HeapPop h for k times.
76+
"""
77+
class Solution(object):
78+
def topKFrequent(self, nums, k):
79+
ans = []
80+
81+
numToCounts = collections.Counter(nums)
82+
h = [(-numToCounts[num], num) for num in numToCounts]
83+
84+
heapq.heapify(h)
85+
86+
while k>0:
87+
_, num = heapq.heappop(h)
88+
ans.append(num)
89+
k -= 1
90+
91+
return ans

0 commit comments

Comments
 (0)