-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path1094.car-pooling.py
48 lines (39 loc) · 1.23 KB
/
1094.car-pooling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#
# @lc app=leetcode id=1094 lang=python3
#
# [1094] Car Pooling
#
# @lc code=start
# TAGS: Greedy
# REVIEWME: Bucket Sort.
import collections
from typing import List
class Solution:
# 52 ms, 99.61%. Time: O(N). Space: O(1). Bucket Sort
# Not good if the value of miles is very large.
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
stations = [0] * 1000
for i in range(len(trips)):
no, start, end = trips[i]
stations[start] += no
stations[end] -= no
total = 0
for no in stations:
total += no
if total > capacity:
return False
return True
# 52 ms, 99.61%. Time: O(NlogN). Space: O(N). Higher Time Complexity but works better in general.
def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
stations = collections.defaultdict(int)
for i in range(len(trips)):
no, start, end = trips[i]
stations[start] += no
stations[end] -= no
total = 0
for station in sorted(stations.keys()):
total += stations[station]
if total > capacity:
return False
return True
# @lc code=end