PancrasL的博客

常见算法的 Java 实现

2021-03-25

See the source image

1. 算法

1.1 DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
* Return true if there is a path from cur to target.
*/
boolean DFS(Node cur, Node target, Set<Node> visited) {
return true if cur is target;
for (next : each neighbor of cur) {
if (next is not in visited) {
add next to visted;
return true if DFS(next, target, visited) == true;
}
}
return false;
}

1.2 BFS

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
/**
* Return the length of the shortest path between root and target node.
*/
int BFS(Node root, Node target) {
Queue<Node> queue; // store all nodes which are waiting to be processed
Set<Node> used; // store all the used nodes
int step = 0; // number of steps neeeded from root to current node
// initialize
add root to queue;
add root to used;
// BFS
while (queue is not empty) {
step = step + 1;
// iterate the nodes which are already in the queue
int size = queue.size();
for (int i = 0; i < size; ++i) {
Node cur = the first node in queue;
return step if cur is target;
for (Node next : the neighbors of cur) {
if (next is not in used) {
add next to queue;
add next to used;
}
}
remove the first node from queue;
}
}
return -1; // there is no path from root to target
}

1.3 最大公约数、最小公倍数

1
2
3
public int gcd(int x, int y) {
return y > 0 ? gcd(y, x % y) : x;
}

1.4 二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int binarySearch(int[] nums, int target) {
int low, high, mid;

low = 0;
high = nums.length - 1;

while (low <= high) {
mid = ((high - low)/2) + low;
if (target == nums[mid]) {
return mid;
} else if (target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return low;
}