KK's blog

每天积累多一些

0%

LeetCode



We are given an array asteroids of integers representing asteroids in a row.

For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.

Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.

Example 1:

Input: asteroids = [5,10,-5]
Output: [5,10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.


Example 2:

Input: asteroids = [8,-8]
Output: []
Explanation: The 8 and -8 collide exploding each other.


Example 3:

Input: asteroids = [10,2,-5]
Output: [10]
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.


Constraints:

2 <= asteroids.length <= 10<sup>4</sup> -1000 <= asteroids[i] <= 1000
* asteroids[i] != 0

题目大意:

星体向左向右同速运动,符号表示方向,数值表示星体大小。若相撞,同大小想消,否则较小的消失。

解题思路:

保持原有顺序且相邻元素大小关系,考虑用Stack

解题步骤:

N/A

注意事项:

  1. 两星体可以正负,所以有四种可能:同左,同右,向左向右,向右向左。只有最后一种向右向左才会相撞。所以出栈条件为栈顶为正,遍历元素为负。
  2. 同大小要特别处理,记录到is_same_size变量中。入栈条件为出栈条件的非以及不是is_same_size

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
stack = []
for i in range(len(asteroids)):
is_same_size = False
while stack and stack[-1] > 0 and asteroids[i] < 0 and -asteroids[i] >= stack[-1]:
stack_top = stack.pop()
if stack_top == -asteroids[i]:
is_same_size = True
break
if not (stack and stack[-1] > 0 and asteroids[i] < 0) and not is_same_size:
stack.append(asteroids[i])
return stack

算法分析:

时间复杂度为O(n),空间复杂度O(n)

更简洁的写法,不要要掌握while, break, else语句,如果没有break,else永远执行,若break,else不执行。若不熟悉该语法,推荐用上法。

Python代码:

1
2
3
4
5
6
7
8
9
def asteroidCollision2(self, asteroids: List[int]) -> List[int]:
stack = []
for i in range(len(asteroids)):
while stack and stack[-1] > 0 and asteroids[i] < 0:
if -asteroids[i] < stack[-1] or stack.pop() == -asteroids[i]:
break
else:
stack.append(asteroids[i])
return stack

LeetCode



Given the root of a binary tree, return the vertical order traversal of its nodes’ values. (i.e., from top to bottom, column by column).

If two nodes are in the same row and column, the order should be from left to right.

Example 1:



Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]


Example 2:



Input: root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]


Example 3:



Input: root = [3,9,8,4,0,1,7,null,null,null,2,5]
Output: [[4],[9,5],[3,0,1],[8,2],[7]]


Constraints:

The number of nodes in the tree is in the range [0, 100]. -100 <= Node.val <= 100

题目大意:

按列顺序打印二叉树

BFS解题思路(推荐):

从root开始从0编号,左右节点分别为-1, 1,如此类推,就可以标记所有节点,从而将这些节点加入结果集。

LeetCode 314 Binary Tree Vertical Order Traversal 同一列,从上到下,从左到右排序
LeetCode 987 Vertical Order Traversal of a Binary Tree 同一列,从上到下,同一行值从小到大排序

解题步骤:

N/A

注意事项:

  1. BFS引入(vertical_id, root)来做计算。由于结果列表如vertical_id = -1, 1可以从左或右加入,用dict来记录vertical到list更好合理
  2. 由于vertical_id是连续的,所以不妨用min_col, max_col来记录dict的范围,保证从dict到结果集是按顺序加入。

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
idx_to_list, res = collections.defaultdict(list), []
queue = collections.deque([(0, root)])
min_col, max_col = float('inf'), float('-inf')
while queue:
vertical_id, node = queue.popleft()
min_col, max_col = min(min_col, vertical_id), max(max_col, vertical_id)
idx_to_list[vertical_id].append(node.val)
if node.left:
queue.append((vertical_id - 1, node.left))
if node.right:
queue.append((vertical_id + 1, node.right))
for i in range(min_col, max_col + 1):
res.append(idx_to_list[i])
return res

算法分析:

时间复杂度为O(n),空间复杂度O(n)


BFS算法II解题思路:

先写了这个,优化后才得到算法I。区别在于keys需要排序

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def verticalOrder1_1(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
idx_to_list, res = collections.defaultdict(list), []
queue = collections.deque([(0, root)])
while queue:
vertical_id, node = queue.popleft()
idx_to_list[vertical_id].append(node.val)
if node.left:
queue.append((vertical_id - 1, node.left))
if node.right:
queue.append((vertical_id + 1, node.right))
sorted_keys = sorted(list(idx_to_list.keys()))
for i in sorted_keys:
res.append(idx_to_list[i])
return res

算法分析:

时间复杂度为O(nlogn),空间复杂度O(n)


DFS算法III解题思路(不推荐):

最开始的思路,很容易错,因为不符合题目的按层遍历的顺序。题目要求同一column的节点是从上到下,从左到右。DFS与此违反。

注意事项:

  1. 要将同一个column节点从上到下从左到右排序,就要记录height和左到右的顺序(height_id, len(idx_to_list[vertical_id]) - 1, root.val)

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def verticalOrder2(self, root: TreeNode) -> List[List[int]]:
idx_to_list, res = collections.defaultdict(list), []
self.dfs(root, 0, 0, idx_to_list)
sorted_keys = sorted(list(idx_to_list.keys()))
for i in sorted_keys:
li = sorted(idx_to_list[i])
res.append([node[2] for node in li])
return res

def dfs(self, root, height_id, vertical_id, idx_to_list):
if not root:
return
idx_to_list[vertical_id].append((height_id, len(idx_to_list[vertical_id]) - 1, root.val))
self.dfs(root.left, height_id + 1, vertical_id - 1, idx_to_list)
self.dfs(root.right, height_id + 1, vertical_id + 1, idx_to_list)

算法分析:

时间复杂度为O(nlogn),空间复杂度O(1)

LeetCode



You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.

Example 1:

Input: s = “abcd”, k = 2
Output: “abcd”
Explanation: There’s nothing to delete.


Example 2:

Input: s = “deeedbbcccbdaa”, k = 3
Output: “aa”
Explanation: First delete “eee” and “ccc”, get “ddbbbdaa”
Then delete “bbb”, get “dddaa”
Finally delete “ddd”, get “aa”


Example 3:

Input: s = “pbbcggttciiippooaais”, k = 2
Output: “ps”


Constraints:

1 <= s.length <= 10<sup>5</sup> 2 <= k <= 10<sup>4</sup>
* s only contains lower case English letters.

题目大意:

字符串中去除连续k次的字符

解题思路:

一开始用暴力法得到LTE。这题由于需要保持顺序,且元素之间是相等关系且类似于LeetCode 316 Remove Duplicate Letters,考虑用Stack。

解题步骤:

N/A

注意事项:

  1. Stack中存元素和该元素的连续个数,这样避免往前重新计算连续了几次。若栈顶元素等于遍历元素且栈顶连续个数为k - 1就连续出栈。此情况此遍历元素不入栈

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def removeDuplicates(self, s: str, k: int) -> str:
stack, res = [], ''
for i in range(len(s)):
if stack and stack[-1][0] == s[i] and stack[-1][1] == k - 1:
while stack and stack[-1][0] == s[i]:
stack.pop()
else:
if stack and stack[-1][0] == s[i]:
stack.append((s[i], stack[-1][1] + 1))
else:
stack.append((s[i], 1))
while stack:
pair = stack.pop()
res += pair[0]
return res[::-1]

算法分析:

时间复杂度为O(n),空间复杂度O(n)

LeetCode



According to Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

Example 1:



Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]


Example 2:



Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]


Constraints:

m == board.length n == board[i].length
1 <= m, n <= 25 board[i][j] is 0 or 1.

Follow up:

Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?

题目大意:

根据临近8个细胞的情况来决定生死。若该细胞是live和临近有2-3个是live,仍然live。若该细胞是dead和临近有3个是live,复生。其他都变成dead

解题思路:

N/A

解题步骤:

N/A

注意事项:

  1. board[:] = res赋值到原数组一定要用冒号

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
OFFSETS = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
class Solution(TestCases):

def gameOfLife(self, board: List[List[int]]) -> None:
res = [[0 for _ in range(len(board[0]))] for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
live_neighbor_num = self.get_live_neighbor_num(board, i, j)
if board[i][j] == 0 and live_neighbor_num == 3:
res[i][j] = 1
if board[i][j] == 1 and live_neighbor_num in [2, 3]:
res[i][j] = 1
board[:] = res

def get_live_neighbor_num(self, board, i, j):
res = 0
for _dx, _dy in OFFSETS:
x, y = i + _dx, j + _dy
if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] == 1:
res += 1
return res

算法分析:

时间复杂度为O(8n2),空间复杂度O(n2)


算法II解题思路O(1) Space:

用一个数字来记录前后状态,2表示从0到1,3表示从1到0

注意事项:

  1. 不同之处有两个: Line 11不再是board[i][j]为1的情况,而是从1变成0的情况: live_neighbor_num not in [2, 3]
  2. 最后扫一遍矩阵,将2和3变回1和0
  3. board[i][j] == 0和board[i][j] == 1不用改,因为从左到有从上到下扫描,到该格时,该格的值并未变,只能是0或1,它的左和上3邻居才变了。

Python代码:

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
OFFSETS = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
class Solution(TestCases):

def gameOfLife2(self, board: List[List[int]]) -> None:
# STATUS = {2: (0, 1), 3: (1, 0)}
for i in range(len(board)):
for j in range(len(board[0])):
live_neighbor_num = self.get_live_neighbor_num2(board, i, j)
if board[i][j] == 0 and live_neighbor_num == 3:
board[i][j] = 2
if board[i][j] == 1 and live_neighbor_num not in [2, 3]:
board[i][j] = 3
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 2:
board[i][j] = 1
if board[i][j] == 3:
board[i][j] = 0

def get_live_neighbor_num2(self, board, i, j):
res = 0
for _dx, _dy in OFFSETS:
x, y = i + _dx, j + _dy
if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] in [1, 3]:
res += 1
return res

算法分析:

时间复杂度为O(8n2),空间复杂度O(1)


算法III解题思路

另外一条follow up是如果matrix无界,可以假设大部分是死细胞,先收集live细胞的list,然后计算live细胞的临近细胞即可

LeetCode



Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds).

Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). Several hits may arrive roughly at the same time.

Implement the HitCounter class:

HitCounter() Initializes the object of the hit counter system. void hit(int timestamp) Records a hit that happened at timestamp (in seconds). Several hits may happen at the same timestamp.
int getHits(int timestamp) Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).

Example 1:

Input
[“HitCounter”, “hit”, “hit”, “hit”, “getHits”, “hit”, “getHits”, “getHits”]
[[], [1], [2], [3], [4], [300], [300], [301]]
Output
[null, null, null, null, 3, null, 4, 3]

Explanation
HitCounter hitCounter = new HitCounter();
hitCounter.hit(1); // hit at timestamp 1.
hitCounter.hit(2); // hit at timestamp 2.
hitCounter.hit(3); // hit at timestamp 3.
hitCounter.getHits(4); // get hits at timestamp 4, return 3.
hitCounter.hit(300); // hit at timestamp 300.
hitCounter.getHits(300); // get hits at timestamp 300, return 4.
hitCounter.getHits(301); // get hits at timestamp 301, return 3.


Constraints:
1 <= timestamp <= 2 * 10<sup>9</sup>
All the calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing). At most 300 calls will be made to hit and getHits.

Follow up: What if the number of hits per second could be huge? Does your design scale?

题目大意:

设计统计hits系统。题目要求:同一个时间可以有多个hits,hit是按时间顺序的。

解题思路:

用一个固定大小为300的数组来记录timestamp和对应的hits的总数

解题步骤:

N/A

注意事项:

  1. 题目要求:同一个时间可以有多个hits,hit是按时间顺序的。所以固定数组只要比较现在的timestamp是否和last_timestamp一样,不是的话reset hit。用循环数组记录
  2. getHist是统计300以内(不包括300)的hit数。

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class HitCounter(TestCases):

def __init__(self):
self.hits = [(0, 0)] * 300

def hit(self, timestamp: int) -> None:
last_timestamp, count = self.hits[timestamp % 300]
if last_timestamp and timestamp != last_timestamp:
self.hits[timestamp % 300] = (timestamp, 0)
count = 0
count += 1
self.hits[timestamp % 300] = (timestamp, count)

def getHits(self, timestamp: int) -> int:
res = 0
for t, count in self.hits:
if t and timestamp - t < 300:
res += count
return res

算法分析:

hit时间复杂度为O(1),getHits时间复杂度为O(1),空间复杂度O(1)

Free mock interview