阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. Queue
1.1 Moving window average
Given a stream of integers and a windows size, calculate the moving average of all integers in the sliding window.
from collections import deque
class MovingAverage(object):
def __init__(self, size):
self.size = size
self.q = deque()
self.sum = 0
def next(self, val):
self.q.append(val)
self.sum += val
if len(self.q) <= self.size:
pass
else:
self.sum -= self.q.popleft()
return 1.0 * self.sum / len(self.q) # float(self.sum / len(self.q))可能return 0.0整理注: Python 3的/已经是真除法;旧注释中的整数除法问题针对Python 2。窗口大小应为正整数。
1.2 Binary tree level order traversal (level by level, left to right)
3
/ \
9 20
/ / \
3 15 7
output: [3, 9, 20, 3, 15, 7]class Solution(object): # TC:O(N)
def levelOrder(self, root):
if not root:
return []
queue = deque([root]) # queue = deque() ; queue.append(root)
result = []
while queue:
node = queue.popleft() # O(1)
result.append(node.value)
# Add child nodes of the current level
# node expansion
if node.left:
queue.append(node.left) # notice: not root!!
if node.right:
queue.append(node.right)
return resultFollow up 1
3
/ \
9 20
/ / \
3 15 7
output: [[3],
[9, 20],
[3, 15, 7]]class Solution1(object): # TC:O(N)
def levelOrder(self, root):
if not root:
return []
queue = deque([root])
result = []
while queue:
count = len(queue) # 当前queue的size,也是当前层的size
current_level = []
for i in range(count):
node = queue.popleft()
current_level.append(node.value)
if node.left:
queue.append(node.left) # notice: not root!!
if node.right:
queue.append(node.right)
result.append(current_level)
return result1.3 Design Circular Queue
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called “Ring Buffer”.
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
class MyCircularQueueWithCount:
def __init__(self, k):
self.array = [None] * k
self.head = 0
self.tail = 0
self.count = 0
def isEmpty(self):
return self.count == 0
def isFull(self):
return self.count == len(self.array)
def enQueue(self, value):
if self.isFull():
return False
self.array[self.tail] = value
self.tail = (self.tail + 1) % len(self.array)
self.count += 1
return True
def deQueue(self):
if self.isEmpty():
return False
self.head = (self.head + 1) % len(self.array)
self.count -= 1
return True
def front(self):
if self.isEmpty():
return -1
else:
return self.array[self.head]
def rear(self):
if self.isEmpty():
return -1
else:
return self.array[(self.tail - 1) % len(self.array)]2. Stack
2.1 Unsorted array, deduplication for adjacent letters repeatedly
a b b b a z w -> a a z w -> z wlinear scan 回头看 ——> use stack
def removeDup(string):
if len(string) <= 1:
return string
stack = []
f = 0
while f < len(string):
if len(stack) > 0 and string[f] == stack[-1]:
while f < len(string) and string[f] == stack[-1]:
f += 1
stack.pop()
else:
stack.append(string[f])
f += 1
return "".join(stack)2.2 逆波兰表达式
1 2 + 3 * 4 / --> (1 + 2) * 3 / 4class Solution(object):
def evalRPN(self, tokens):
if len(tokens) == 0:
return 0
st = []
for i in range(len(tokens)):
if tokens[i] == '+':
r = st.pop()
l = st.pop()
st.append(l + r)
elif tokens[i] == '-':
r = st.pop()
l = st.pop()
st.append(l - r)
elif tokens[i] == '*':
r = st.pop()
l = st.pop()
st.append(l * r)
elif tokens[i] == '/':
r = st.pop()
l = st.pop()
st.append((abs(l) // abs(r)) * (-1 if (l < 0) != (r < 0) else 1))
else:
st.append(int(tokens[i]))
return st.pop()3. Heap
TC:
1. insert: O(logN)
2. update: O(logN)
3. get/top: O(1)
4. pop: O(logN)
5. heapify: O(cN) ~ O(2N)3.1 Top K frequent elements
-
Solution 1:
max heap, python use min heap, so (-frequency, value) -
Solution 2:
用逻辑上min heap, K-size min heap, 不断push, 不断把小的pop
优势:省内存,空间复杂度好
import heapq
def topFrequentPQ(nums, k):
# 统计 O(n)
freq_hash = dict()
for n in nums:
if n in freq_hash:
freq_hash[n] += 1
else:
freq_hash[n] = 1
heap = []
for n, f in freq_hash.items(): # O(NlogK)
heapq.heappush(heap, (f, n))
if len(heap) > k:
heapq.heappop(heap)
ret = []
while len(heap) != 0: # O(KlogK)
ret.append(heapq.heappop(heap)[1])
ret.reverse() # O(K)
return ret