排序
快排
public static <T extends Comparable<T>> void qSort(T[] arr){
if (arr == null || arr.length <= 1) return;
qSort(arr, 0, arr.length-1);
}
private static <T extends Comparable<T>> void qSort(T[] arr, int start, int end){
if (start >= end)return;
int i = start, j = end;
while (i < j){
while (j > i && arr[j].compareTo(arr[start]) > 0)j--;
while (i < j && arr[i].compareTo(arr[start]) <= 0)i++;
if (i < j){
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
T tmp = arr[i];
arr[i] = arr[start];
arr[start] = tmp;
qSort(arr, start, i-1);
qSort(arr, i+1, end);
}
堆排序
public static void heapSort(int[] arr){
if (arr == null || arr.length <= 1)return;
heapSort(arr, arr.length);
}
public static void heapSort(int[] arr, int length) {
for (int i = length/2; i >= 0 ; i--) {
percolateDown(arr, i, length);
}
for (int i = 0; i < length; i++){
swap(arr, 0, length-1-i);
percolateDown(arr, 0, length-1-i);
}
}
private static void percolateDown(int[] arr, int hole, int length) {
int tmp = arr[hole], child = 2*hole;
for (; 2*hole+1 < length; hole = child){
child = 2*hole+1;
if (child+1 < length && arr[child+1] < arr[child])child++;
if (arr[child] < tmp){
arr[hole] = arr[child];
}
}
arr[hole] = tmp;
}
归并排序
public static void mergeSort(int[] arr){
if (arr == null || arr.length <= 1)return;
mergeSort(arr, 0, arr.length-1);
}
public static void mergeSort(int[] arr, int s, int e) {
if (s < e){
int m = (s + e) >> 1;
mergeSort(arr, s, m);
mergeSort(arr, m+1, e);
merge(arr, s, m, e);
}
}
private static void merge(int[] arr, int s, int m, int e) {
int[] tmp = new int[e-s+1];
int k = 0, j = m+1, i = s;
while (i <= m && j <= e){
if (arr[i] < arr[j]){
tmp[k++] = arr[i++];
}else{
tmp[k++] = arr[j++];
}
}
while (i <= m){
tmp[k++] = arr[i++];
}
while (j <= e){
tmp[k++] = arr[j++];
}
k = 0;
while (k < tmp.length){
arr[s+k] = tmp[k++];
}
}
二叉树
层次遍历
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
int count = 0;
while (!stack.isEmpty()) {
int size = stack.size();
while (size-- > 0) {
TreeNode cur = stack.pop();
if (cur.left != null)
stack.addLast(cur.left);
if (cur.right != null)
stack.addLast(cur.right);
}
count++;
}
return count;
}
Misc
BFS
int BFS(Node start, Node target) {
Queue<Node> q;
Set<Node> visited;
q.offer(start);
visited.add(start);
int step = 0;
while (q not empty) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
Node cur = q.poll();
if (cur is target)
return step;
for (Node x : cur.adj())
if (x not in visited) {
q.offer(x);
visited.add(x);
}
}
step++;
}
}