KK's blog

每天积累多一些

0%

算法思路:

定义: 栈里元素维持由栈底到栈顶从大到小的顺序叫递减栈。跟最小堆一样,递减栈的栈首元素最小

反之是递增栈,不过此法因为用递减栈比较多,所以统称递减栈。通常是将下标而不是值放入到栈中,这样还可以知道元素间的距离。

求较大值 -> 递减栈
求较小值 -> 递增栈

递减栈 vs heap
实现上几乎一样,详见算法知识点目录。区别在于元素间是否需要保持顺序或者是否是stream

应用:

  1. 数组不能打乱顺序且求极值

注意事项:

  1. 跟最小堆一样,当元素大于栈顶元素的时候才倒逼栈内元素出栈。
  2. 记得是stack[-1]看栈顶元素不是stack[0]

Python代码:

1
2
3
4
5
6
stack = []
for i in range(len(li)):
while stack and li[i] > li[stack[-1]]:
index = stack.pop()

stack.append(i)

LeetCode 503 Next Greater Element II 核心思想: 原数组复制一遍,用新数组完全做一遍递减栈,最后才截取结果
结果数组默认值为-1而不是0,这样不用处理stack剩下的元素

例子:

1
2
3
4
5
6
7
8
9
10
# [1, 2], [2, 1]
def nextGreaterElements(self, nums: List[int]) -> List[int]:
nums_copy = nums * 2
stack, res = [], [-1] * len(nums_copy)
for i in range(len(nums_copy)):
while stack and nums_copy[i] > nums_copy[stack[-1]]:
index = stack.pop()
res[index] = nums_copy[i]
stack.append(i)
return res[:len(nums)]

算法分析:

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

算法思路:

Leetcode 208 Implement Trie (Prefix Tree), 也可以用HashMap将所有前缀加入到Map来实现,效率稍低。

适用条件:

prefix搜索和文件系统
变体:Trie+DFS, search中迭代变递归,详见算法知识目录

注意事项:

  1. TrieNode用{}和is_end,insert, search, startswith用it和i迭代比较
  2. startswith含整个单词,如单词apple,startswith('apple') -> True
  3. ~~Line 11记得加,也就是dict在取value是一定要先检验key是否存在。~~可以不加,解决方案是用defaultdict(后版本)。

新版本比旧版本更简洁,体现在is_end的处理放在了for循环外。
存储结构举例: a

1
2
3
4
5
6
TrieNode(
children = {
'a': TrieNode(is_End = True)
}
is_end = False
)

实现思路:

  1. 数据结构为多叉树defaultdict(TrieNode)
  2. 实现用链表来迭代写,self.head是fake node
  3. search和startsWith的遍历指针从head开始,比较指针的子节点(下一位)和s[i]. 不能比较指针是否为空, 因为it=it.children[s[i]]后,it就肯定不会空,由于defaultdict

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

def __init__(self):
self.head = TrieNode()

def insert(self, word: str) -> None:
it = self.head
for i in range(len(word)):
# if word[i] not in it.children:
#it.children[word[i]] = TrieNode()
it = it.children[word[i]]
it.is_end = True

def search(self, word: str) -> bool:
it = self.head
for i in range(len(word)):
if word[i] not in it.children:
return False
it = it.children[word[i]]
return it.is_end

def startsWith(self, prefix: str) -> bool:
it = self.head
for i in range(len(prefix)):
if prefix[i] not in it.children:
return False
it = it.children[prefix[i]]
return True

class TrieNode:

def __init__(self):
self.children = collections.defaultdict(TrieNode) # {}
self.is_end = False

旧版本: 冗余了一个if语句if i == len(word) - 1

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
41
42
43
44
45
class Trie(TestCases):

def __init__(self):
self.head = TrieNode()

def insert(self, word: str) -> None:
if not word:
return
it = self.head
for i in range(len(word)):
# if word[i] not in it.children:
# it.children[word[i]] = TrieNode()
it = it.children[word[i]]
if i == len(word) - 1:
it.is_end = True

def search(self, word: str) -> bool:
if not word:
return False
it = self.head
for i in range(len(word)):
if word[i] not in it.children:
return False
it = it.children[word[i]]
if i == len(word) - 1 and it.is_end:
return True
return False

def startsWith(self, prefix: str) -> bool:
if not prefix:
return False
it = self.head
for i in range(len(prefix)):
if prefix[i] not in it.children:
return False
it = it.children[prefix[i]]
if i == len(prefix) - 1:
return True
return False

class TrieNode:

def __init__(self):
self.children = collections.defaultdict(TrieNode) # {}
self.is_end = False

算法分析:

每个操作时间复杂度为O(n),空间复杂度O(n),n为单词长度。

算法思路:

  1. 递归找pivot,然后按小于pivot和大于等于pivot分成两组。每轮递归,pivot肯定在正确(最终)位置上
  2. partition方法类似于Leetcode75的sort colors一样用两个指针i和noSmallerIdx。i是循环指针,而
    noSmallerIdx是第二组大于等于pivot的首元素. 由于前面已经分为两部分了,所以nums[i]只有比pivot小才需要交换到前面,否则符合顺序,不用交换
  3. 循环结束后,将pivot交换到正确的位置上。


i指向4,因为4小于pivot,所以要换到前面去,跟6置换,noSmallerIdx向后移。

注意事项:

  1. range(start, end)不含end,因为end指向pivot

应用:

  1. 排序
  2. 快速选择quick select
  3. partition,如Leetcode 75

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def quick_sort(self, nums: List[int]):
if not nums:
return
self.q_sort(nums, 0, len(nums) - 1)

def q_sort(self, nums: List[int], start: int, end: int):
if start >= end:
return
pivot = self.partition(nums, start, end)
self.q_sort(nums, start, pivot - 1)
self.q_sort(nums, pivot + 1, end)

def partition(self, nums: List[int], start: int, end: int):
no_smaller_index, pivot = start, end
for i in range(start, end):
if nums[i] < nums[pivot]:
nums[no_smaller_index], nums[i] = nums[i], nums[no_smaller_index]
no_smaller_index += 1
nums[no_smaller_index], nums[end] = nums[end], nums[no_smaller_index]
return no_smaller_index

算法分析:

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

Quick Select

选择第k小的数(下标从0开始)

注意事项:

  1. left > right不再是等于,因为几个数相等的情况,排序的时候不用再移动,但第k小里面需要继续递归。
  2. binary select是单边递归,而不是双边。要判断pivot是否等于k。
  3. 递归调用仍用k,而不是跟pivot_pos相关,因为k是下标位置
  4. partition中range用[start, end)而不是len

Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def quick_select(self, nums: List[int], k: int) -> int:
if not nums:
return -1
return self.q_select(nums, 0, len(nums) - 1, k)

def q_select(self, nums: List[int], start: int, end: int, k: int):
if start > end:
return -1
pivot = self.partition(nums, start, end)
if k == pivot:
return nums[pivot]
if k < pivot:
return self.q_select(nums, start, pivot - 1, k)
else:
return self.q_select(nums, pivot + 1, end, k)

算法分析:

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

Partition

用于原位排序,将相应的元素放入该放的位置直到不满足条件为止

注意事项:

  1. i不一定会移动,放在else里面

1
2
3
4
5
6
7
8
9
10
def sort(self, nums: List[int]) -> int:
i = 0
while i < len(nums):
if <condition>
self.swap(nums, i, j)
else:
i += 1

def swap(self, nums, i, j):
nums[i], nums[j] = nums[j], nums[i]

上述算法的问题不能有效处理两种情况:

  1. 有序数组[1, 2, 3, 4]
  2. 单一数组[2, 2, 2, 2]

第一种情况递归为 [123] [12] [1] 只会递归左半,不会递归右半

第二种情况 [2222] [222] [22] [2] 只会递归右半,不会递归左半 这两种情况都是O(n^2)

解决第一个问题用randomize pivot的方法 解决第二个问题用three-way partition的方法,类似于75 Sort colors将区间从两个变成3个: 小于pivot, 等于pivot,大于pivot,这样对于单一值数组,左半和右半就不会递归了

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
def sortArray(self, nums: List[int]) -> List[int]:
if not nums:
return
self.q_sort(nums, 0, len(nums) - 1)
return nums


def q_sort(self, nums: List[int], start: int, end: int):
if start >= end:
return
pivot = random.randint(start, end)
nums[pivot], nums[start] = nums[start], nums[pivot]
lt, gt = self.partition(nums, start, end)
self.q_sort(nums, start, lt - 1)
self.q_sort(nums, gt, end)

def partition(self, x, start, end):
i, lt, gt = start, start, end
while i <= gt and i < len(x) and gt >= 0:
if x[i] < x[lt]:
x[i], x[lt] = x[lt], x[i]
i += 1
lt += 1
elif x[i] > x[lt]:
x[i], x[gt] = x[gt], x[i]
gt -= 1
else: # x[i] == x[lt]
i += 1
return lt, gt

Java代码:

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
public void sort(int[] arr) {
if(arr == null || arr.length == 0)
return;
quickSort(arr, 0, arr.length - 1);
}

void quickSort(int[] arr, int left, int right) {
if(left >= right)
return;
int pivotPos = partition(arr, left, right);
quickSort(arr, left, pivotPos - 1);
quickSort(arr, pivotPos + 1, right);
}

int partition(int[] arr, int left, int right) {
int noSmallerIdx = left;
int pivot = arr[right];
for(int i = left; i < right; i++) {
if(arr[i] < pivot)
swap(arr, noSmallerIdx++, i);
}
swap(arr, noSmallerIdx, right);
return noSmallerIdx;
}

void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

括号题

算法思路:

  1. 优先考虑用Stack。Stack可以将字符压入比较或者字符的下标压入比较,后者信息量更大
    三种情况不合法: '[' (stack有余,for后发生), ']' (要匹配的时候stack为空,for中发生), '{]' (不匹配,for中发生)
  2. DP
    1. 左括号的数量在每一位都大于等于右括号数量
    2. 右括号的总和要等于右括号总和
      以上两个条件都满足的话,左右括号匹配,但此法只能用于单种括号

应用:

  1. 括号题
  2. 字符串运算题如, 3+4, (3+4)*5

括号运算题

stack的作用是存储优先级较低的操作数(暂时不能计算) 定义公式

res是作为同一层的临时计算结果,若遇到左括号,res保留在stack中且reset,若遇到右括号,stack的结果还原到res
num也是临时变量负责储存整数

注意事项:

  1. char.isdigit()的计算
  2. 左括号:入栈和reset res和num。
  3. 右括号:出栈和还原res = tmp + f(res)。

括号运算题模板:

1
2
3
4
5
6
7
8
9
10
def parenthesis(self, s: str) -> int:
(Optional) s边界处理如s += '+'
stack, num = [], 0 数据结构用stack以及stack的一个元素
for char in s:
所有字符的可能情况
比如
if char.isdigit():
num = num * 10 + int(char)
如果某情况入栈就一定要重置参数num=0
如果某情况出栈,代入公式计算

算法分析:

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

LeetCode 394 Decode String

两个stack存储优先级较低的字符以及数字,类似于多重括号2*(3*(4)) 公式:prev_res+prev_num*[res]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def decodeString(self, s: str) -> str:
stack_num, stack_char, num, char_str = [], [], 0, ""
# char_str + num[<>]
for c in s:
if c.isdigit():
num = 10 * num + int(c)
if c.isalpha():
char_str += c
if c == "[":
stack_num.append(num)
stack_char.append(char_str)
num = 0
char_str = ""
if c == "]":
prev_char = stack_char.pop()
prev_num = stack_num.pop()
char_str = prev_char + prev_num * char_str
return char_str

LeetCode 227 Basic Calculator II

stack=只存加号操作符 核心思想是只有出现运算符,才能计算前一个数[op]num. 所以op和num是记录前一个符号和数字 字符三种类别:空格,数字和运算符
若遇到运算符,就处理四种的op,目标是都要把num压栈,但是op是乘除要计算积或商后才能压栈。压栈后num=0, 若5*6+, char="+"的时候, prev = "5", prev_op = "*", num="6".
公式: [prev][prev_op][num][c=op]
实现时候先写只有加减的,再处理乘除,思维从简单开始。注意减法容易遗漏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def calculate(self, s: str) -> int:
# prev_num[prev_op]num, 2+3+4+, 2+3*4+
stack, prev_op, num = [], '+', 0
s += "+"
for c in s:
if c == "":
continue
if c.isdigit():
num = num * 10 + int(c)
elif c in '+-*/':
if prev_op in '*/':
prev_num = stack.pop()
if prev_op == "*":
num = prev_num * num
else:
num = int(prev_num / num)
if prev_op == "-":
num = -num
stack.append(num)
num = 0
prev_op = c
return sum(stack)

算法思路:

DFS用于需要知道具体路径的问题,而并查集方法用于不需知道具体路径只关心连通性的问题。
此算法把同一个连通集归结为同一个根节点,作为判断是否一个连通集的标识。它用深度为2的扁平树组织起来。这是查找操作。
另一个关键操作是联合两个不同连通集,就是直接把根节点直接作为另一课树的子节点。在这个过程中,新的树深度可能会大于2,但当要union路径大于2的节点是,会对其进行路径压缩。
最巧妙的操作当属find操作,将路径进行压缩,变成长度为1的路径,见步骤4。
可能有人会考虑用HashMap而不是树,HashMap查找也是很高效,但联合操作比较费时,因为要更新另一个树的所有节点的根节点。

算法步骤:

  1. 初始化UnionFind类,包括3个属性:count(独立连通数), parent(某节点的父节点), rank(连通集排名,只有每个连通集根节点的rank不为0,其他点均为0。这是一个描述连通集规模的变量,如果规模越大,
    rank值可能越大。合并时候,rank较小的话,规模也较小,这样用rank小的合并到rank大的,需要压缩路径的节点较少,复杂度更低)。合格的节点的parent初始化为自己的id,rank为0,count为所有合格节点数量。
  2. 遍历所有节点,union此节点及其相邻的节点(如上下左右)
  3. union时候,先find两节点的根节点,若相同忽略。若不同,合并此两连通集:rank大的连通集,作为rank小的连通集的父节点。若rank相等,选任一作为另一个的父节点且把它的rank加1。count减1。
    如下图,union 5和1的,find(6)会进行压缩路径,把6接到5下。
  4. find寻找根节点的同时,压缩成与根节点路径为1的连通。

例子矩阵: {'0','1','1','0','0'} {'1','1','1','0','0'}

应用条件:

动态计算连通数如305. Number of Islands II

注意事项:

  1. find中是if语句不是while语句,因为递归已经达到
  2. union中,是祖先节点相连,不是输入相连
  3. union的调用在类外面调用,不是在init里做

实现思路:

  1. 数据结构为a->b的父子parent[a]=b关系defaultdict(str)
  2. find实现用来DFS写,先找到root,将所有节点连到root

Python代码:

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

def __init__(self, li):
self.parents = collections.defaultdict(str)
for s in li:
self.parents[s] = s

def find(self, s):
if self.parents[s] == s:
return s
root = self.find(self.parents[s])
return root

def union(self, s1, s2):
root1, root2 = self.find(s1), self.find(s2)
self.parents[root2] = root1 # remember not self.parent[s] = s2

注意事项:

find要注意压缩路径parent[i] = find(parent[i])

初始化:

1
2
3
4
5
6
7
8
9
10
class UnionFind {
int[] parent;

public Initialization(int n) {
// initialize your data structure here.
parent = new int[n + 1];
for (int i = 1; i <= n; ++i)
father[i] = i;
}
}

查找:

1
2
3
4
5
6
public int find(int i) {
if (parent[i] != i) {
parent[i] = find(parent[i]); // path compression
}
return parent[i];
}

合并:

1
2
3
4
5
6
public void union(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if (root_a != root_b)
parent[root_a] = root_b;
}

Java代码:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
class UnionFind {
int count; // # of connected components
int[] parent;
int[] rank;

public UnionFind(char[][] grid) { // for problem 200
count = 0;
int m = grid.length;
int n = grid[0].length;
parent = new int[m * n];
rank = new int[m * n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == '1') {
parent[i * n + j] = i * n + j;
++count;
}
rank[i * n + j] = 0;
}
}
}

public int find(int i) {
if (parent[i] != i) {
parent[i] = find(parent[i]); // path compression
}
return parent[i];
}

// union point x and y with rank
public void union(int x, int y) {
int rootx = find(x);
int rooty = find(y);
if (rootx != rooty) {
if (rank[rootx] > rank[rooty]) {
parent[rooty] = rootx;
} else if (rank[rootx] < rank[rooty]) {
parent[rootx] = rooty;
} else {
parent[rooty] = rootx;
rank[rootx] += 1;
}
--count;
}
}

public int getCount() {
return count;
}
}

public int numIslands3(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}

int nr = grid.length;
int nc = grid[0].length;
int num_islands = 0;
UnionFind uf = new UnionFind(grid);
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
grid[r][c] = '0';
if (r - 1 >= 0 && grid[r - 1][c] == '1') {
uf.union(r * nc + c, (r - 1) * nc + c);
}
if (r + 1 < nr && grid[r + 1][c] == '1') {
uf.union(r * nc + c, (r + 1) * nc + c);
}
if (c - 1 >= 0 && grid[r][c - 1] == '1') {
uf.union(r * nc + c, r * nc + c - 1);
}
if (c + 1 < nc && grid[r][c + 1] == '1') {
uf.union(r * nc + c, r * nc + c + 1);
}
}
}
}

return uf.getCount();
}

算法分析:

时间复杂度为O(MN),空间复杂度O(MN)。M,N分别为矩阵长宽。遍历每个节点,而每个节点只会遍历4个相邻节点。

Ref:

并查集(Union-Find)算法介绍

Free mock interview