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



You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.

There are two types of logs:

Letter-logs: All words (except the identifier) consist of lowercase English letters. Digit-logs: All words (except the identifier) consist of digits.

Reorder these logs so that:

1. The letter-logs come before all digit-logs.
2. The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The digit-logs maintain their relative ordering.

Return the final order of the logs.

Example 1:

Input: logs = [“dig1 8 1 5 1”,”let1 art can”,”dig2 3 6”,”let2 own kit dig”,”let3 art zero”]
Output: [“let1 art can”,”let3 art zero”,”let2 own kit dig”,”dig1 8 1 5 1”,”dig2 3 6”]
Explanation:
The letter-log contents are all different, so their ordering is “art can”, “art zero”, “own kit dig”.
The digit-logs have a relative order of “dig1 8 1 5 1”, “dig2 3 6”.


Example 2:

Input: logs = [“a1 9 2 3 1”,”g1 act car”,”zo4 4 7”,”ab1 off key dog”,”a8 act zoo”]
Output: [“g1 act car”,”a8 act zoo”,”ab1 off key dog”,”a1 9 2 3 1”,”zo4 4 7”]


Constraints:

1 <= logs.length <= 100 3 <= logs[i].length <= 100
All the tokens of logs[i] are separated by a single space. logs[i] is guaranteed to have an identifier and at least one word after the identifier.

题目大意:

排序log file,以下顺序:字母log (内容,id), 数字log

解题思路(推荐):

N/A

解题步骤:

N/A

注意事项:

  1. 排序的multi key实现(0, content_str, li[0]) if is_alpha else (1, ). (1, )表示按数组顺序

Python代码:

1
2
3
4
5
6
7
8
9
def reorderLogFiles(self, logs: List[str]) -> List[str]:

def get_key(x):
li = x.split(' ')
content_str = ' '.join(li[1:])
is_alpha = 1 if content_str[0].isalpha() else 0
return (0, content_str, li[0]) if is_alpha else (1, )

return sorted(logs, key=get_key)

算法分析:

时间复杂度为O(nmlogn),空间复杂度O(mn), n为log数量,m为每个log的最长长度。如mergesort中merge复杂度为nm, 每个key比较是O(m)复杂度


算法II解题思路:

我的解法。本质上和上法一致,较繁琐

注意事项:

  1. 字母log排序不能按content_str + ‘ ‘ + li[0], 而是(content_str, li[0])作多key排序

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
def reorderLogFiles2(self, logs: List[str]) -> List[str]:
letter_logs, digit_logs = [], []
for i in range(len(logs)):
if logs[i][-1].isdigit():
digit_logs.append(logs[i])
else:
li = logs[i].split(' ')
content_str = ' '.join(li[1:])
letter_logs.append((content_str, li[0], i))
letter_logs.sort()
res = [logs[pair[2]] for pair in letter_logs]
res += digit_logs
return res

LeetCode



Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key’s value at a certain timestamp.

Implement the TimeMap class:

TimeMap() Initializes the object of the data structure. void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.
String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns "".

Example 1:

Input
[“TimeMap”, “set”, “get”, “get”, “set”, “get”, “get”]
[[], [“foo”, “bar”, 1], [“foo”, 1], [“foo”, 3], [“foo”, “bar2”, 4], [“foo”, 4], [“foo”, 5]]
Output
[null, null, “bar”, “bar”, null, “bar2”, “bar2”]

Explanation
TimeMap timeMap = new TimeMap();
timeMap.set(“foo”, “bar”, 1); // store the key “foo” and value “bar” along with timestamp = 1.
timeMap.get(“foo”, 1); // return “bar”
timeMap.get(“foo”, 3); // return “bar”, since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is “bar”.
timeMap.set(“foo”, “bar2”, 4); // store the key “foo” and value “bar2” along with timestamp = 4.
timeMap.get(“foo”, 4); // return “bar2”
timeMap.get(“foo”, 5); // return “bar2”


Constraints:
1 <= key.length, value.length <= 100
key and value consist of lowercase English letters and digits. 1 <= timestamp <= 10<sup>7</sup>
All the timestamps timestamp of set are strictly increasing. At most 2 * 10<sup>5</sup> calls will be made to set and get.

题目大意:

实现带历史记录的HashMap。也就是同一个key记录所有赋过值的value

解题思路:

N/A

解题步骤:

N/A

注意事项:

  1. Map to list的思路,list含两个,包括value和timestamp,用binary search搜索timestamp的下标,然后返回对应的value

Python代码:

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

def __init__(self):
self.key_to_val = collections.defaultdict(list)
self.key_to_timestamp = collections.defaultdict(list)

def set(self, key: str, value: str, timestamp: int) -> None:
self.key_to_val[key].append(value)
self.key_to_timestamp[key].append(timestamp)

def get(self, key: str, timestamp: int) -> str:
index = bisect.bisect(self.key_to_timestamp[key], timestamp) - 1
if index == -1:
return ''
else:
return self.key_to_val[key][index]

算法分析:

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

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。实现类似于BST的后序遍历,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细胞的临近细胞即可

Free mock interview