KK's blog

每天积累多一些

0%

LeetCode

<div>

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:

<pre>Input: s = "abcd", k = 2 Output: "abcd" Explanation: There's nothing to delete.</pre>

Example 2:

<pre>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"</pre>

Example 3:

<pre>Input: s = "pbbcggttciiippooaais", k = 2 Output: "ps" </pre>

Constraints:

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

</div>

题目大意:

字符串中去除连续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

<div>

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.

<span>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.</span>

Example 1:

<pre>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]] </pre>

Example 2:

<pre>Input: board = [[1,1],[1,0]] Output: [[1,1],[1,1]] </pre>

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?

</div>

题目大意:

根据临近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

算法分析:

时间复杂度为<code>O(8n<sup>2</sup>)</code>,空间复杂度<code>O(n<sup>2</sup>)</code>


算法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

算法分析:

时间复杂度为<code>O(8n<sup>2</sup>)</code>,空间复杂度O(1)


算法III解题思路

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

LeetCode

<div>

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:

<pre>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. </pre>

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?

</div>

题目大意:

设计统计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)

LeetCode

<div>

Given an array of strings words and an integer k, return the k most frequent strings.

Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.

Example 1:

<pre>Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["i","love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. </pre>

Example 2:

<pre>Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4 Output: ["the","is","sunny","day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. </pre>

Constraints:

  • 1 <= words.length <= 500
  • 1 <= words[i] <= 10
  • words[i] consists of lowercase English letters.
  • k is in the range [1, The number of **unique** words[i]]

Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?

</div>

题目大意:

求k个最高频率的单词

解题思路:

N/A

解题步骤:

N/A

注意事项:

  1. 若频率一样,就按字母顺序lexicographical. 所以用大小为k的heap做比较困难。直接用排序即可

Python代码:

1
2
3
4
5
def topKFrequent(self, words: List[str], k: int) -> List[str]:
freq_dict = collections.Counter(words)
li = [(freq, word) for word, freq in freq_dict.items()]
li.sort(key=lambda x : (-x[0], x[1]))
return [pair[1] for pair in li[:k]]

算法分析:

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

LeetCode

<div>

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

<pre>Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000</pre>

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral.

Example 1:

<pre>Input: num = 3 Output: "III" Explanation: 3 is represented as 3 ones. </pre>

Example 2:

<pre>Input: num = 58 Output: "LVIII" Explanation: L = 50, V = 5, III = 3. </pre>

Example 3:

<pre>Input: num = 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. </pre>

Constraints:

  • 1 <= num <= 3999

</div>

题目大意:

阿拉伯数字转罗马数字

解题思路(推荐):

本质上和算法二一样,但优化了代码。map的内容是一样的但变成list保证顺序,然后从大到小遍历这个map,商对应的symbol放入结果,余数进入下一轮

注意事项:

  1. map的内容是一样的但变成list保证顺序,然后从大到小遍历这个map,商对应的symbol放入结果,余数进入下一轮

Python代码:

1
2
3
4
5
6
7
8
9
def intToRoman(self, num: int) -> str:
INT_TO_ROMAN = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'),
(90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'),
(4, 'IV'), (1, 'I')]
res = ''
for n, symbol in INT_TO_ROMAN:
count, num = num // n, num % n
res += symbol * count
return res

算法分析:

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


算法II解题思路:

N/A

解题步骤:

N/A

注意事项:

  1. 用int to english的递归方法,将固定值放入到Map中
  2. 分界点为[4, 5, 9 10], [40, 50, 90, 100]进行递归

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def intToRoman2(self, num: int) -> str:
INT_TO_ROMAN = {
0: '',
4: 'IV',
5: 'V',
9: 'IX',
10: 'X',
40: 'XL',
50: 'L',
90: 'XC',
100: 'C',
400: 'CD',
500: 'D',
900: 'CM',
1000: 'M',
}
if num in INT_TO_ROMAN:
return INT_TO_ROMAN[num]
elif num < 4:
return 'I' * num
elif num < 9:
return self.intToRoman(5) + self.intToRoman(num - 5)
elif num < 40:
return 'X' * (num // 10) + self.intToRoman(num % 10)
elif num < 50:
return self.intToRoman(40) + self.intToRoman(num - 40)
elif num < 90:
return self.intToRoman(50) + self.intToRoman(num - 50)
elif num < 100:
return self.intToRoman(90) + self.intToRoman(num % 90)
elif num < 400:
return 'C' * (num // 100) + self.intToRoman(num % 100)
elif num < 500:
return self.intToRoman(400) + self.intToRoman(num - 400)
elif num < 900:
return self.intToRoman(500) + self.intToRoman(num - 500)
elif num < 1000:
return self.intToRoman(900) + self.intToRoman(num % 900)
else:
return 'M' * (num // 1000) + self.intToRoman(num % 1000)

算法分析:

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

Free mock interview