Skip to content

Commit bd5f193

Browse files
committedNov 18, 2020
2020-11-18
1 parent 719c957 commit bd5f193

File tree

8 files changed

+308
-68
lines changed

8 files changed

+308
-68
lines changed
 

‎0079.单词搜索/0079-单词搜索.py

+22-25
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,31 @@ def exist(self, board, word):
77
"""
88
if not board or not board[0]:
99
return False
10-
if not word:
11-
return True
12-
13-
self.res = False
10+
11+
m, n = len(board), len(board[0])
1412
dx = [1, -1, 0, 0]
1513
dy = [0, 0, 1, -1]
16-
def dfs(start, x0, y0):
17-
if start == len(word) - 1:
14+
self.res = False
15+
def dfs(word_idx, x0, y0):
16+
# print word_idx
17+
if word_idx >= len(word):
1818
self.res = True
19-
return
20-
visited.add((x0, y0))
21-
22-
for k in range(4):
23-
x = x0 + dx[k]
24-
y = y0 + dy[k]
25-
# print x, y
26-
if 0 <= x < m and 0 <= y < n and (x, y) not in visited and board[x][y] == word[start + 1] and not self.res:
27-
visited.add((x, y))
28-
dfs(start + 1, x, y)
29-
visited.remove((x, y))
30-
31-
m, n = len(board), len(board[0])
32-
# print m * n, len(word)
19+
return
20+
if not self.res:
21+
for k in range(len(dx)):
22+
x1 = x0 + dx[k]
23+
y1 = y0 + dy[k]
24+
25+
if 0 <= x1 < m and 0 <= y1 < n and board[x1][y1] == word[word_idx]:
26+
temp = board[x1][y1]
27+
board[x1][y1] = -1
28+
dfs(word_idx + 1, x1, y1)
29+
board[x1][y1] = temp
3330
for i in range(m):
3431
for j in range(n):
3532
if board[i][j] == word[0]:
36-
visited = set()
37-
dfs(0, i, j)
38-
if self.res:
39-
return True
40-
return False
33+
temp = board[i][j]
34+
board[i][j] = 0
35+
dfs(1, i, j)
36+
board[i][j] = temp
37+
return self.res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution(object):
9+
def verticalOrder(self, root):
10+
"""
11+
:type root: TreeNode
12+
:rtype: List[List[int]]
13+
"""
14+
if not root:
15+
return None
16+
17+
from collections import defaultdict, deque
18+
19+
queue = deque([(0, root)])
20+
res = defaultdict(list) # key is column idx in the result, value is all elements that have that idx
21+
while queue:
22+
col_idx, node = queue.popleft()
23+
24+
res[col_idx].append(node.val)
25+
26+
if node.left:
27+
queue.append((col_idx - 1, node.left))
28+
if node.right:
29+
queue.append((col_idx + 1, node.right))
30+
31+
return [val for idx, val, in sorted(res.items(), key=lambda x: x[0])]
32+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import random
2+
class RandomizedSet(object):
3+
4+
def __init__(self):
5+
"""
6+
Initialize your data structure here.
7+
"""
8+
self.dic = dict()
9+
self.l = []
10+
11+
def insert(self, val):
12+
"""
13+
Ins
14+
from typing import ValuesViewerts a value to the set. Returns true if the set did not already contain the specified element.
15+
:type val: int
16+
:rtype: bool
17+
"""
18+
if val in self.dic:
19+
return False
20+
else:
21+
self.l.append(val)
22+
self.dic[val] = len(self.l) - 1
23+
return True
24+
25+
26+
def remove(self, val):
27+
"""
28+
Removes a value from the set. Returns true if the set contained the specified element.
29+
:type val: int
30+
:rtype: bool
31+
"""
32+
33+
if val not in self.dic:
34+
return False
35+
else:
36+
# get the index of the element to be delted
37+
index = self.dic[val]
38+
self.dic.pop(val)
39+
40+
# swap the element with the last element
41+
self.l[index], self.l[-1] = self.l[-1], self.l[index]
42+
43+
if index != len(self.l) - 1:
44+
# if swap happened, update the index of element that got swapped
45+
self.dic[self.l[index]] = index
46+
47+
self.l.pop()
48+
49+
return True
50+
51+
52+
53+
def getRandom(self):
54+
"""
55+
Get a random element from the set.
56+
:rtype: int
57+
"""
58+
59+
return random.choice(self.l)
60+
61+
62+
63+
# Your RandomizedSet object will be instantiated and called as such:
64+
# obj = RandomizedSet()
65+
# param_1 = obj.insert(val)
66+
# param_2 = obj.remove(val)
67+
# param_3 = obj.getRandom()

‎0445.两数相加II/0445-两数相加II.py

+59-30
Original file line numberDiff line numberDiff line change
@@ -11,39 +11,68 @@ def addTwoNumbers(self, l1, l2):
1111
:type l2: ListNode
1212
:rtype: ListNode
1313
"""
14-
s1, s2 = [], []
15-
while l1:
16-
s1.append(l1.val)
14+
def getLinkedListLength(l):
15+
length = 0
16+
while l:
17+
l = l.next
18+
length += 1
19+
return length
20+
21+
def printLL(node):
22+
l = []
23+
while node:
24+
l.append(node.val)
25+
node = node.next
26+
print(l)
27+
28+
def reverseLL(node):
29+
if not node or not node.next:
30+
return node
31+
p = reverseLL(node.next)
32+
node.next.next = node
33+
node.next = None
34+
return p
35+
36+
length1 = getLinkedListLength(l1)
37+
length2 = getLinkedListLength(l2)
38+
39+
if length1 < length2:
40+
l1, l2 = l2, l1
41+
length1, length2 = length2, length1
42+
43+
dummy = ListNode(-1)
44+
p = dummy
45+
46+
n = length1 - length2
47+
while n:
48+
p.next = ListNode(l1.val)
1749
l1 = l1.next
18-
50+
p = p.next
51+
n -= 1
52+
1953
while l2:
20-
s2.append(l2.val)
54+
p.next = ListNode(l1.val + l2.val)
55+
p = p.next
56+
l1 = l1.next
2157
l2 = l2.next
22-
58+
59+
60+
dummy.next = reverseLL(dummy.next)
61+
62+
p = dummy.next
2363
carry = 0
24-
cur = ListNode(-1)
25-
while s1 or s2:
26-
value = carry
27-
if s1:
28-
value += s1.pop()
29-
if s2:
30-
value += s2.pop()
31-
32-
carry = value > 9
33-
value %= 10
34-
35-
cur.val = value
36-
pre = ListNode(-1)
37-
pre.next = cur
38-
cur = pre
39-
40-
if carry: #´¦Àí¿ÉÄܵĽøÎ»
41-
pre.val = 1
42-
return pre
43-
44-
return pre.next
64+
pre = dummy
65+
while p:
66+
p.val += carry
67+
if p.val > 9:
68+
p.val -= 10
69+
carry = 1
70+
else:
71+
carry = 0
72+
p = p.next
73+
pre = pre.next
4574

46-
47-
75+
if carry:
76+
pre.next = ListNode(1)
4877

49-
78+
return reverseLL(dummy.next)
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution(object):
2+
def candyCrush(self, board):
3+
"""
4+
:type board: List[List[int]]
5+
:rtype: List[List[int]]
6+
"""
7+
if not board or not board[0]:
8+
return None
9+
10+
m, n = len(board), len(board[0])
11+
# 1. crush stage
12+
13+
# flag all elements to be crushed
14+
todo = 0
15+
for i in range(m):
16+
for j in range(n - 2):
17+
if board[i][j] and abs(board[i][j]) == abs(board[i][j + 1]) == abs(board[i][j + 2]):
18+
board[i][j] = board[i][j + 1] = board[i][j + 2] = -abs(board[i][j])
19+
todo = 1
20+
21+
for j in range(n):
22+
for i in range(m - 2):
23+
if board[i][j] and abs(board[i][j]) == abs(board[i + 1][j]) == abs(board[i + 2][j]):
24+
board[i][j] = board[i + 1][j] = board[i + 2][j] = -abs(board[i][j])
25+
todo = 1
26+
# print board, todo
27+
# 2. gravity stage
28+
for j in range(n):
29+
lo, hi = m - 1, m - 1
30+
while hi >= 0:
31+
while hi >= 0 and board[hi][j] < 0:
32+
hi -= 1
33+
34+
if hi >= 0:
35+
board[lo][j] = board[hi][j]
36+
lo -= 1
37+
hi -= 1
38+
39+
while lo >= 0:
40+
board[lo][j] = 0
41+
lo -= 1
42+
43+
# recursively call this function if more crush is necessary
44+
return self.candyCrush(board) if todo else board

‎0797.所有可能的路径/0797-所有可能的路径.py

+8-13
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,14 @@ def allPathsSourceTarget(self, graph):
44
:type graph: List[List[int]]
55
:rtype: List[List[int]]
66
"""
7-
res = list()
87
n = len(graph)
9-
def dfs(start, tmp):
10-
if graph[start] == [] and start == n - 1:#ûÓÐÏÂÒ»¸ö½Úµã
11-
tmp += graph[start]
12-
res.append(tmp[:])
8+
visited = set()
9+
def dfs(cur_node, path):
10+
if cur_node == n - 1:
11+
res.append(path[:])
1312
return
14-
15-
l = graph[start]
16-
for node in l:
17-
tmp.append(node)
18-
dfs(node, tmp)
19-
tmp.pop()
20-
21-
dfs(0, [0])
13+
for next_node in graph[cur_node]:
14+
dfs(next_node, path + [next_node])
15+
res = []
16+
dfs(0, [0])
2217
return res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode(object):
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.left = None
6+
# self.right = None
7+
8+
class Solution(object):
9+
def verticalTraversal(self, root):
10+
"""
11+
:type root: TreeNode
12+
:rtype: List[List[int]]
13+
"""
14+
from collections import defaultdict
15+
dic = defaultdict(list)
16+
def dfs(root, x, y):
17+
if root:
18+
dic[x].append((y, root.val))
19+
dfs(root.left, x - 1, y + 1)
20+
dfs(root.right, x + 1, y + 1)
21+
22+
dfs(root, 0, 0)
23+
res = []
24+
for k in sorted(dic.keys()):
25+
x = [pair[1] for pair in sorted(dic[k])]
26+
res.append(x)
27+
28+
return res
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class UndergroundSystem(object):
2+
3+
def __init__(self):
4+
self.check_in_history = dict() # key is id + stationName, val is t
5+
self.StationTraverlTime = dict()
6+
def checkIn(self, id, stationName, t):
7+
"""
8+
:type id: int
9+
:type stationName: str
10+
:type t: int
11+
:rtype: None
12+
"""
13+
self.check_in_history[str(id)] = [stationName, t]
14+
15+
16+
def checkOut(self, id, stationName, t):
17+
"""
18+
:type id: int
19+
:type stationName: str
20+
:type t: int
21+
:rtype: None
22+
"""
23+
start_station, start_time = self.check_in_history[str(id)]
24+
self.check_in_history.pop(str(id))
25+
time_spent = t - start_time
26+
key = start_station + "#" + stationName
27+
if key not in self.StationTraverlTime:
28+
self.StationTraverlTime[key] = [time_spent,1]
29+
else:
30+
self.StationTraverlTime[key][0] += time_spent
31+
self.StationTraverlTime[key][1] += 1
32+
33+
34+
def getAverageTime(self, startStation, endStation):
35+
"""
36+
:type startStation: str
37+
:type endStation: str
38+
:rtype: float
39+
"""
40+
key = startStation + "#" + endStation
41+
return self.StationTraverlTime[key][0] * 1.0 / self.StationTraverlTime[key][1]
42+
43+
44+
# Your UndergroundSystem object will be instantiated and called as such:
45+
# obj = UndergroundSystem()
46+
# obj.checkIn(id,stationName,t)
47+
# obj.checkOut(id,stationName,t)
48+
# param_3 = obj.getAverageTime(startStation,endStation)

0 commit comments

Comments
 (0)
Please sign in to comment.