• Java数据结构与算法


    基本知识
    时间复杂度

    评估算法优劣的核心指标是什么?

    时间复杂度(流程决定)
    额外空间复杂度(流程决定)
    常数项时间(实现细节决定)

    什么是时间复杂度?时间复杂度怎么估算?

    常数时间的操作
    确定算法流程的总操作数量与样本数量之间的表达式关系
    只看表达式最高阶项的部分

    何为常数时间的操作?

    如果一个操作的执行时间不以具体样本量为转移,每次执行时间都是固定时间。称这样的操作为常数时间的操作。

    常见的常数时间的操作

    ● 常见的算术运算(+、-、*、/、% 等)
    ● 常见的位运算(>>、>>>、<<、|、&、^等)
    ● 赋值、比较、自增、自减操作等
    ● 数组寻址操作

    如何确定算法流程的时间复杂度?

    当完成了表达式的建立,只要把最高阶项留下即可。低阶项都去掉,高阶项的系数也去掉。
    记为:O(忽略掉系数的高阶项)

    时间复杂度的意义

    时间复杂度的意义在于:
    当我们要处理的样本量很大很大时,我们会发现低阶项是什么不是最重要的;每一项的系数是什么,不是最重要的。真正重要的就是最高阶项是什么。
    这就是时间复杂度的意义,它是衡量算法流程的复杂程度的一种指标,该指标只与数据量有关,与过程之外的优化无关。

    常见的时间复杂度

    排名从好到差:
    O(1)
    O(logN)
    O(N)
    O(N*logN)
    O(N^2) O(N^3) … O(N^K)
    O(2^N) O(3^N) … O(K^N)
    O(N!)

    额外空间复杂度
    你要实现一个算法流程,在实现算法流程的过程中,你需要开辟一些空间来支持你的算法流程。
    作为输入参数的空间,不算额外空间。作为输出结果的空间,也不算额外空间。
    因为这些都是必要的、和现实目标有关的。所以都不算。
    但除此之外,你的流程如果还需要开辟空间才能让你的流程继续下去。这部分空间就是额外空间。
    如果你的流程只需要开辟有限几个变量,额外空间复杂度就是O(1)。

    对数器
    认识对数器
    【Java算法】06_对数器

    认识对数器

    1、你想要测的方法a
    2、实现复杂度不好但是容易实现的方法b
    3、实现一个随机样本产生器
    4、把方法a和方法b跑相同的随机样本,看看得到的结果是否一样
    5、如果有一个随机样本使得比对结果不一致,打印样本进行人工干预,改对方法a和方法b
    6、当样本数量很多时比对测试依然正确,可以确定方法a已经正确。

    排序算法
    选择排序

    基本思想:每一趟从待排序的数据元素中选择最小(或最大)的一个元素作为首元素,直到所有元素为止。
    算法实现:每一趟通过不断地比较交换来使得首元素为当前最小,交换是一个比较耗时间的操作。我们可以通过设置一个值来记录较小元素的下标,循环结束后存储的当前最小元素的下标,这时在进行交换就可以了。

    public class SelectionSort {

    public static void selectionSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            // 最小值在哪个位置上  i~n-1
            int minIndex = i;
            for (int j = i; i < arr.length; j++) { // i ~ N-1 上找最小值的下标
                minIndex = arr[j] < arr[minIndex] ? j : minIndex;
            }
            swap(arr, i, minIndex);
        }
    }
    
    // 交换
    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    }

    冒泡排序
    它重复地走访过要排序的元素列,依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们交换过来。走访元素的工作是重复地进行,直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
    这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧化碳)的气泡最终会上浮到顶端一样,故名“冒泡排序”。

    原理
    1、比较相邻的元素。如果第一个比第二个大,就交换他们两个
    2、对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
    3、针对所有的元素重复以上的步骤,除了最后一个。
    4、持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

    代码实现
    // 冒泡排序
    public class BubbleSort {
    public static void bubbleSort(int[] arr) {
    if (arr == null || arr.length < 2) {
    return;
    }

        for (int e = arr.length - 1; e > 0; e--) { // 0 ~ e
            for (int i = 0; i < e; i++) {
                if (arr[i] > arr[i + 1]) {
                    swap(arr, i, i + 1);
                }
            }
        }
    }
    
    // 交换arr的i和j位置上的值
    public static void swap(int[] arr, int i, int j) {
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    }
    插入排序

    过程:
    想让arr[0~0]上有序,这个范围只有一个数,当然是有序的。
    想让arr[0~1]上有序,所以从arr[1]开始往前看,如果arr[1]
    想让arr[0~i]上有序,所以从arr[i]开始往前看,arr[i]这个数不停向左移动,一直移动到左边的数字不再比自己大,停止移动。
    最后一步,想让arr[0~N-1]上有序, arr[N-1]这个数不停向左移动,一直移动到左边的数字不再比自己大,停止移动。

    // 插入排序
    public class InsertionSort {

    public static void insertionSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
    
        for (int i = 1; i < arr.length; i++) {
            // arr[i]往前看,一直交换到合适的位置停止
            for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
                swap(arr, j, j + 1);
            }
        }
    }
    
    public static void swap(int[] arr, int i, int j) {
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    }
    归并排序
    1)整体是递归,左边排好序+右边排好序+merge让整体有序
    2)让其整体有序的过程里用了排外序方法
    3)利用master公式来求解时间复杂度
    4)当然可以用非递归实现
    时间复杂度
    T(N) = 2T(N/2) + O(N^1)
    根据master可知时间复杂度为O(N
    logN)
    merge过程需要辅助数组,所以额外空间复杂度为O(N)
    归并排序的实质是把比较行为变成了有序信息并传递,比O(N^2)的排序快
    public class MergeSort {

    public static void merge(int[] arr, int L, int M, int R) {
    	int[] help = new int[R - L + 1];
    	int i = 0;
    	int p1 = L;
    	int p2 = M + 1;
    	while (p1 <= M && p2 <= R) {
    		help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
    	}
    	while (p1 <= M) {
    		help[i++] = arr[p1++];
    	}
    	while (p2 <= R) {
    		help[i++] = arr[p2++];
    	}
    	for (i = 0; i < help.length; i++) {
    		arr[L + i] = help[i];
    	}
    }
    
    // 递归方法实现
    public static void mergeSort1(int[] arr) {
    	if (arr == null || arr.length < 2) {
    		return;
    	}
    	process(arr, 0, arr.length - 1);
    }
    
    public static void process(int[] arr, int L, int R) {
    	if (L == R) {
    		return;
    	}
    	int mid = L + ((R - L) >> 1);
    	process(arr, L, mid);
    	process(arr, mid + 1, R);
    	merge(arr, L, mid, R);
    }
    
    • 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

    }
    快速排序
    在arr[L…R]范围上,进行快速排序的过程:
    1)在这个范围上,随机选一个数记为num,
    1)用num对该范围做partition,< num的数在左部分,== num的数中间,>num的数在右部分。假设== num的数所在范围是[a,b]
    2)对arr[L…a-1]进行快速排序(递归)
    3)对arr[b+1…R]进行快速排序(递归)因为每一次partition都会搞定一批数的位置且不会再变动,所以排序能完成
    时间复杂度分析
    1)通过分析知道,划分值越靠近中间,性能越好;越靠近两边,性能越差
    2)随机选一个数进行划分的目的就是让好情况和差情况都变成概率事件
    3)把每一种情况都列出来,会有每种情况下的时间复杂度,但概率都是1/N
    4)那么所有情况都考虑,时间复杂度就是这种概率模型下的长期期望!时间复杂度O(N*logN),额外空间复杂度O(logN)都是这么来的。
    public class Code03_PartitionAndQuickSort {

    public static void swap(int[] arr, int i, int j) {
    	int tmp = arr[i];
    	arr[i] = arr[j];
    	arr[j] = tmp;
    }
    
    public static int[] netherlandsFlag(int[] arr, int L, int R) {
    	if (L > R) {
    		return new int[] { -1, -1 };
    	}
    	if (L == R) {
    		return new int[] { L, R };
    	}
    	int less = L - 1;
    	int more = R;
    	int index = L;
    	while (index < more) {
    		if (arr[index] == arr[R]) {
    			index++;
    		} else if (arr[index] < arr[R]) {
    			swap(arr, index++, ++less);
    		} else {
    			swap(arr, index, --more);
    		}
    	}
    	swap(arr, more, R);
    	return new int[] { less + 1, more };
    }
    
    public static void quickSort(int[] arr) {
    	if (arr == null || arr.length < 2) {
    		return;
    	}
    	process3(arr, 0, arr.length - 1);
    }
    
    public static void process(int[] arr, int L, int R) {
    	if (L >= R) {
    		return;
    	}
    	swap(arr, L + (int) (Math.random() * (R - L + 1)), R);
    	int[] equalArea = netherlandsFlag(arr, L, R);
    	process(arr, L, equalArea[0] - 1);
    	process(arr, equalArea[1] + 1, R);
    }
    
    • 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

    }
    堆排序
    1)堆结构就是用数组实现的完全二叉树结构2)
    完全二叉树中如果每棵子树的最大值都在顶部就是大根堆
    3)完全二叉树中如果每棵子树的最小值都在顶部就是小根堆
    4)堆结构的heapInsert与heapify操作
    5)堆结构的增大和减少
    6)优先级队列结构,就是堆结构
    语言提供的堆结构 vs 手写的堆结构
    取决于,你有没有动态改信息的需求!
    语言提供的堆结构,如果你动态改数据,不保证依然有序
    手写堆结构,因为增加了对象的位置表,所以能够满足动态改信息的需求
    大根堆

    小根堆

    从上往下建堆 O(logN)

    从下往上建堆 O(N)

    从下往上建堆比从上往下建堆要快。

    桶排序
    计数排序
    基数排序

    比较器
    1)比较器的实质就是重载比较运算符
    2)比较器可以很好的应用在特殊标准的排序上
    3)比较器可以很好的应用在根据特殊标准排序的结构上
    4)写代码变得异常容易,还用于范型编程
    同一规定
    即如下方法:
    @Override
    public int compare(T o1, T o2)
    ;返回负数的情况,就是o1比o2优先的情况
    返回正数的情况,就是o2比o1优先的情况
    返回0的情况,就是o1与o2同样优先的情况

    排序算法总结
    时间复杂度 额外空间复杂度 稳定性
    选择排序 O(N^2) O(1) 无
    冒泡排序 O(N^2) O(1) 有
    插入排序 O(N^2) O(1) 有
    归并排序 O(NlogN) O(N) 有
    随机快排 O(N
    logN) O(logN) 无
    堆排序 O(N*logN) O(1) 无

    计数排序 O(N) O(M) 有
    基数排序 O(N) O(N) 有

    1)不基于比较的排序,对样本数据有严格要求,不易改写
    2)基于比较的排序,只要规定好两个样本怎么比大小就可以直接复用
    3)基于比较的排序,时间复杂度的极限是O(NlogN)
    4)时间复杂度O(N
    logN)、额外空间复杂度低于O(N)、且稳定的基于比较的排序是不存在的。
    5)为了绝对的速度选快排、为了省空间选堆排、为了稳定性选归并

    常见的坑
    1)归并排序的额外空间复杂度可以变成O(1),“归并排序 内部缓存法”,但是将变得不再稳定。
    2)“原地归并排序" 是垃圾贴,会让时间复杂度变成O(N^2)
    3)快速排序稳定性改进,“01 stable sort”,但是会对样本数据要求更多。

    二分查找

    位运算
    异或运算
    异或运算:相同为0,不同为1
    能长时间记住的概率接近0%
    所以,异或运算就记成无进位相加!
    异或运算的性质
    1)0^N == N N^N == 0
    2)异或运算满足交换律和结合率

    如何不用额外变量交换两个数

    // 交换i和j的值
    public static void swap(int i, int j) {
    	i = i ^ j;
    	j = i ^ j;
    	i = i ^ j;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    链表

    单向链表节点结构
    public class Node {
    public int value;
    public Node next;
    public Node(int data) {
    value = data;
    }
    }

    双向链表节点结构

    public class DoubleNode {
    public int value;
    public DoubleNode last;
    public DoubleNode next;

    public DoubleNode(int data) {
        value = data;
    }
    
    • 1
    • 2
    • 3

    }

    反转单向链表

    public static Node reverseLinkedList(Node head) {
    	Node pre = null;
    	Node next = null;
    	while (head != null) {
    		next = head.next;
    		head.next = pre;
    		pre = head;
    		head = next;
    	}
    	return pre;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    反转双向链表

    public static DoubleNode reverseDoubleList(DoubleNode head) {
    	DoubleNode pre = null;
    	DoubleNode next = null;
    	while (head != null) {
    		next = head.next;
    		head.next = pre;
    		head.last = next;
    		pre = head;
    		head = next;
    	}
    	return pre;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    移除链表上的某个值

    public class Code02_DeleteGivenValue {

    public static class Node {
    	public int value;
    	public Node next;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    public static Node removeValue(Node head, int num) {
    	while (head != null) {
    		if (head.value != num) {
    			break;
    		}
    		head = head.next;
    	}
    	Node pre = head;
    	Node cur = head;
    	while (cur != null) {
    		if (cur.value == num) {
    			pre.next = cur.next;
    		} else {
    			pre = cur;
    		}
    		cur = cur.next;
    	}
    	return head;
    }
    
    • 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

    }

    使用快慢指针输出中点
    class Code01_LinkedListMid {

    public static class Node {
        public int value;
        public Node next;
    
        public Node(int v) {
            value = v;
        }
    }
    
    //输入链表头节点,奇数长度返回中点,偶数长度返回上中点
    public static Node midOrUpMidNode(Node head) {
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        Node slow = head.next;
        Node fast = head.next.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    // 输入链表头节点,奇数长度返回中点,偶数长度返回下中点
    public static Node midOrDownMidNode(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node slow = head.next;
        Node fast = head.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    // 输入链表头节点,奇数长度返回中点前一个,偶数长度返回上中点前一个
    public static Node midOrUpMidPreNode(Node head) {
        if (head == null || head.next == null || head.next.next == null) {
            return null;
        }
        Node slow = head;
        Node fast = head.next.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    // 输入链表头节点,奇数长度返回中点前一个,偶数长度返回下中点前一个
    public static Node midOrDownMidPreNode(Node head) {
        if (head == null || head.next == null) {
            return null;
        }
        if (head.next.next == null) {
            return head;
        }
        Node slow = head;
        Node fast = head.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    • 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

    }

    链表是否是回文链表
    public class Code02_IsPalindromeList {

    public static class Node {
    	public int value;
    	public Node next;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    // need n extra space
    // 把链表全部进栈,利用栈的先进后出特性,相当于把链表逆序了
    public static boolean isPalindrome1(Node head) {
    	Stack stack = new Stack();
    	Node cur = head;
    	while (cur != null) {
    		stack.push(cur);
    		cur = cur.next;
    	}
    	while (head != null) {
    		if (head.value != stack.pop().value) {
    			return false;
    		}
    		head = head.next;
    	}
    	return true;
    }
    
    // need n/2 extra space
    // 只把一半链表入栈
    public static boolean isPalindrome2(Node head) {
    	if (head == null || head.next == null) {
    		return true;
    	}
    	Node right = head.next;
    	Node cur = head;
    	while (cur.next != null && cur.next.next != null) {
    		right = right.next;
    		cur = cur.next.next;
    	}
    	Stack stack = new Stack();
    	while (right != null) {
    		stack.push(right);
    		right = right.next;
    	}
    	while (!stack.isEmpty()) {
    		if (head.value != stack.pop().value) {
    			return false;
    		}
    		head = head.next;
    	}
    	return true;
    }
    
    // need O(1) extra space
    public static boolean isPalindrome3(Node head) {
    	if (head == null || head.next == null) {
    		return true;
    	}
    	Node n1 = head; // n1就是慢指针
    	Node n2 = head; // n2就是快指针
    	while (n2.next != null && n2.next.next != null) { // find mid node
    		n1 = n1.next; // n1 -> mid
    		n2 = n2.next.next; // n2 -> end
    	}
    	n2 = n1.next; // n2 -> right part first node
    	n1.next = null; // mid.next -> null
    	Node n3 = null;
        // 把后半的节点逆序
    	while (n2 != null) { // right part convert
    		n3 = n2.next; // n3 -> save next node
    		n2.next = n1; // next of right node convert
    		n1 = n2; // n1 move
    		n2 = n3; // n2 move
    	}
    	n3 = n1; // n3 -> save last node
    	n2 = head;// n2 -> left first node
    	boolean res = true;
    	while (n1 != null && n2 != null) { // check palindrome
    		if (n1.value != n2.value) {
    			res = false;
    			break;
    		}
    		n1 = n1.next; // left to mid
    		n2 = n2.next; // right to mid
    	}
    	n1 = n3.next;
    	n3.next = null;
        // 把链表的后半节点重写逆序回来
    	while (n1 != null) { // recover list
    		n2 = n1.next;
    		n1.next = n3;
    		n3 = n1;
    		n1 = n2;
    	}
    	return res;
    }
    
    public static void printLinkedList(Node node) {
    	System.out.print("Linked List: ");
    	while (node != null) {
    		System.out.print(node.value + " ");
    		node = node.next;
    	}
    	System.out.println();
    }
    
    public static void main(String[] args) {
    
    	Node head = null;
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(1);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	head.next.next = new Node(3);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	head.next.next = new Node(1);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	head.next.next = new Node(3);
    	head.next.next.next = new Node(1);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	head.next.next = new Node(2);
    	head.next.next.next = new Node(1);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	head.next.next = new Node(3);
    	head.next.next.next = new Node(2);
    	head.next.next.next.next = new Node(1);
    	printLinkedList(head);
    	System.out.print(isPalindrome1(head) + " | ");
    	System.out.print(isPalindrome2(head) + " | ");
    	System.out.println(isPalindrome3(head) + " | ");
    	printLinkedList(head);
    	System.out.println("=========================");
    
    }
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197

    }

    链表按照某值划分小于在左边,等于区域在中间,大于在右边。
    public class Code03_SmallerEqualBigger {

    public static class Node {
    	public int value;
    	public Node next;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    // 使用数组进行做荷兰国旗问题,
    public static Node listPartition1(Node head, int pivot) {
    	if (head == null) {
    		return head;
    	}
    	Node cur = head;
    	int i = 0;
    	while (cur != null) {
    		i++;
    		cur = cur.next;
    	}
    	Node[] nodeArr = new Node[i];
    	i = 0;
    	cur = head;
    	for (i = 0; i != nodeArr.length; i++) {
    		nodeArr[i] = cur;
    		cur = cur.next;
    	}
    	arrPartition(nodeArr, pivot);
    	for (i = 1; i != nodeArr.length; i++) {
    		nodeArr[i - 1].next = nodeArr[i];
    	}
    	nodeArr[i - 1].next = null;
    	return nodeArr[0];
    }
    
    public static void arrPartition(Node[] nodeArr, int pivot) {
    	int small = -1;
    	int big = nodeArr.length;
    	int index = 0;
    	while (index != big) {
    		if (nodeArr[index].value < pivot) {
    			swap(nodeArr, ++small, index++);
    		} else if (nodeArr[index].value == pivot) {
    			index++;
    		} else {
    			swap(nodeArr, --big, index);
    		}
    	}
    }
    
    public static void swap(Node[] nodeArr, int a, int b) {
    	Node tmp = nodeArr[a];
    	nodeArr[a] = nodeArr[b];
    	nodeArr[b] = tmp;
    }
    
    // 使用6个变量进行划分
    public static Node listPartition2(Node head, int pivot) {
    	Node sH = null; // small head
    	Node sT = null; // small tail
    	Node eH = null; // equal head
    	Node eT = null; // equal tail
    	Node mH = null; // big head
    	Node mT = null; // big tail
    	Node next = null; // save next node
    	// every node distributed to three lists
    	while (head != null) {
    		next = head.next;
    		head.next = null;
    		if (head.value < pivot) {
    			if (sH == null) {
    				sH = head;
    				sT = head;
    			} else {
    				sT.next = head;
    				sT = head;
    			}
    		} else if (head.value == pivot) {
    			if (eH == null) {
    				eH = head;
    				eT = head;
    			} else {
    				eT.next = head;
    				eT = head;
    			}
    		} else {
    			if (mH == null) {
    				mH = head;
    				mT = head;
    			} else {
    				mT.next = head;
    				mT = head;
    			}
    		}
    		head = next;
    	}
    	// small and equal reconnect
        // 小于区域的尾巴连等于区域的头,等于区域的尾巴连大于区域的头
    	if (sT != null) { // 如果有小于区域
    		sT.next = eH;
    		eT = eT == null ? sT : eT; // 下一步,谁去连大于区域的头,谁就变成eT
    	}
    	// 上面的if,不管跑了没有,et
    	// all reconnect
    	if (eT != null) { // 如果小于区域和等于区域,不是都没有
    		eT.next = mH;
    	}
    	return sH != null ? sH : (eH != null ? eH : mH);
    }
    
    public static void printLinkedList(Node node) {
    	System.out.print("Linked List: ");
    	while (node != null) {
    		System.out.print(node.value + " ");
    		node = node.next;
    	}
    	System.out.println();
    }
    
    public static void main(String[] args) {
    	Node head1 = new Node(7);
    	head1.next = new Node(9);
    	head1.next.next = new Node(1);
    	head1.next.next.next = new Node(8);
    	head1.next.next.next.next = new Node(5);
    	head1.next.next.next.next.next = new Node(2);
    	head1.next.next.next.next.next.next = new Node(5);
    	printLinkedList(head1);
    	// head1 = listPartition1(head1, 4);
    	head1 = listPartition2(head1, 5);
    	printLinkedList(head1);
    
    }
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133

    }

    单向链表有一个Random,如果深度拷贝这个单向链表
    public class Code04_CopyListWithRandom {

    public static class Node {
    	public int value;
    	public Node next;
    	public Node rand;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    // 把节点以及对应的克隆节点存入到map中
    public static Node copyListWithRand1(Node head) {
    	HashMap map = new HashMap();
    	Node cur = head;
    	while (cur != null) {
    		map.put(cur, new Node(cur.value));
    		cur = cur.next;
    	}
    	cur = head;
    	while (cur != null) {
    		// cur 老
    		// map.get(cur) 新
    		map.get(cur).next = map.get(cur.next);
    		map.get(cur).rand = map.get(cur.rand);
    		cur = cur.next;
    	}
    	return map.get(head);
    }
    
    public static Node copyListWithRand2(Node head) {
    	if (head == null) {
    		return null;
    	}
    	Node cur = head;
    	Node next = null;
    	// copy node and link to every node
    	// 1 -> 2
    	// 1 -> 1' -> 2
    	while (cur != null) {
    		// cur 老 next 老的下一个
    		next = cur.next;
    		cur.next = new Node(cur.value);
    		cur.next.next = next;
    		cur = next;
    	}
    	cur = head;
    	Node curCopy = null;
    	// set copy node rand
    	// 1 -> 1' -> 2 -> 2'
    	while (cur != null) {
    		// cur 老
    		// cur.next  新 copy
    		next = cur.next.next;
    		curCopy = cur.next;
    		curCopy.rand = cur.rand != null ? cur.rand.next : null;
    		cur = next;
    	}
        // 新链表的头节点
    	Node res = head.next;
    	cur = head;
    	// split
        // 把整个链表分离出老链表和新链表
    	while (cur != null) {
    		next = cur.next.next;
    		curCopy = cur.next;
    		cur.next = next;
    		curCopy.next = next != null ? next.next : null;
    		cur = next;
    	}
    	return res;
    }
    
    public static void printRandLinkedList(Node head) {
    	Node cur = head;
    	System.out.print("order: ");
    	while (cur != null) {
    		System.out.print(cur.value + " ");
    		cur = cur.next;
    	}
    	System.out.println();
    	cur = head;
    	System.out.print("rand:  ");
    	while (cur != null) {
    		System.out.print(cur.rand == null ? "- " : cur.rand.value + " ");
    		cur = cur.next;
    	}
    	System.out.println();
    }
    
    public static void main(String[] args) {
    	Node head = null;
    	Node res1 = null;
    	Node res2 = null;
    	printRandLinkedList(head);
    	res1 = copyListWithRand1(head);
    	printRandLinkedList(res1);
    	res2 = copyListWithRand2(head);
    	printRandLinkedList(res2);
    	printRandLinkedList(head);
    	System.out.println("=========================");
    
    	head = new Node(1);
    	head.next = new Node(2);
    	head.next.next = new Node(3);
    	head.next.next.next = new Node(4);
    	head.next.next.next.next = new Node(5);
    	head.next.next.next.next.next = new Node(6);
    
    	head.rand = head.next.next.next.next.next; // 1 -> 6
    	head.next.rand = head.next.next.next.next.next; // 2 -> 6
    	head.next.next.rand = head.next.next.next.next; // 3 -> 5
    	head.next.next.next.rand = head.next.next; // 4 -> 3
    	head.next.next.next.next.rand = null; // 5 -> null
    	head.next.next.next.next.next.rand = head.next.next.next; // 6 -> 4
    
    	printRandLinkedList(head);
    	res1 = copyListWithRand1(head);
    	printRandLinkedList(res1);
    	res2 = copyListWithRand2(head);
    	printRandLinkedList(res2);
    	printRandLinkedList(head);
    	System.out.println("=========================");
    
    }
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124

    }

    单链表是否有环,如果有环则输出第一个入环节点

    /**

    • Definition for singly-linked list.
    • class ListNode {
    • int val;
      
      • 1
    • ListNode next;
      
      • 1
    • ListNode(int x) {
      
      • 1
    •     val = x;
      
      • 1
    •     next = null;
      
      • 1
    • }
      
      • 1
    • }
      */
      public class Solution {
      public ListNode detectCycle(ListNode head) {
      if (head == null || head.next == null || head.next.next == null) {
      return null;
      }
      ListNode slow = head.next;
      ListNode fast = head.next.next;
      while (slow != fast) {
      if (fast.next == null || fast.next.next == null) {
      return null;
      }
      slow = slow.next;
      fast = fast.next.next;
      }
      fast = head;
      while (fast != slow) {
      slow = slow.next;
      fast = fast.next;
      }
      return slow;
      }
      }

    两个链表是否相交,如果相交返回第一个相交的节点。
    1、两个链表都是无环
    如果两个无环链表相交的话,就是后面一部分相交。那可以先把两个链表处理成相同长度,然后一同往后移动并且进行对比,当有一个相同的话就是相交。如果到null了还是没有相同的,则说明没有相交
    2、两个链表都是有环
    两个链表有三种情况:
    1)两个链表 不想交
    2)两个链表相交,相交点在环外
    3)两个链表相交,相交点在环内
    不存在一个有环一个无环的链表的情况。
    public class Code05_FindFirstIntersectNode {

    public static class Node {
    	public int value;
    	public Node next;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    public static Node getIntersectNode(Node head1, Node head2) {
    	if (head1 == null || head2 == null) {
    		return null;
    	}
    	Node loop1 = getLoopNode(head1);
    	Node loop2 = getLoopNode(head2);
    	if (loop1 == null && loop2 == null) {
    		return noLoop(head1, head2);
    	}
    	if (loop1 != null && loop2 != null) {
    		return bothLoop(head1, loop1, head2, loop2);
    	}
    	return null;
    }
    
    // 找到链表第一个入环节点,如果无环,返回null
    public static Node getLoopNode(Node head) {
    	if (head == null || head.next == null || head.next.next == null) {
    		return null;
    	}
    	// n1 慢  n2 快
    	Node n1 = head.next; // n1 -> slow
    	Node n2 = head.next.next; // n2 -> fast
    	while (n1 != n2) {
    		if (n2.next == null || n2.next.next == null) {
    			return null;
    		}
    		n2 = n2.next.next;
    		n1 = n1.next;
    	}
    	n2 = head; // n2 -> walk again from head
    	while (n1 != n2) {
    		n1 = n1.next;
    		n2 = n2.next;
    	}
    	return n1;
    }
    
    // 如果两个链表都无环,返回第一个相交节点,如果不想交,返回null
    public static Node noLoop(Node head1, Node head2) {
    	if (head1 == null || head2 == null) {
    		return null;
    	}
    	Node cur1 = head1;
    	Node cur2 = head2;
    	int n = 0;
    	while (cur1.next != null) {
    		n++;
    		cur1 = cur1.next;
    	}
    	while (cur2.next != null) {
    		n--;
    		cur2 = cur2.next;
    	}
    	if (cur1 != cur2) {
    		return null;
    	}
    	// n  :  链表1长度减去链表2长度的值
    	cur1 = n > 0 ? head1 : head2; // 谁长,谁的头变成cur1
    	cur2 = cur1 == head1 ? head2 : head1; // 谁短,谁的头变成cur2
    	n = Math.abs(n);
    	while (n != 0) {
    		n--;
    		cur1 = cur1.next;
    	}
    	while (cur1 != cur2) {
    		cur1 = cur1.next;
    		cur2 = cur2.next;
    	}
    	return cur1;
    }
    
    // 两个有环链表,返回第一个相交节点,如果不想交返回null
    public static Node bothLoop(Node head1, Node loop1, Node head2, Node loop2) {
    	Node cur1 = null;
    	Node cur2 = null;
    	if (loop1 == loop2) { // 说明两个链表在环外就已经相交
    		cur1 = head1;
    		cur2 = head2;
    		int n = 0;
    		while (cur1 != loop1) {
    			n++;
    			cur1 = cur1.next;
    		}
    		while (cur2 != loop2) {
    			n--;
    			cur2 = cur2.next;
    		}
    		cur1 = n > 0 ? head1 : head2;
    		cur2 = cur1 == head1 ? head2 : head1;
    		n = Math.abs(n);
    		while (n != 0) {
    			n--;
    			cur1 = cur1.next;
    		}
    		while (cur1 != cur2) {
    			cur1 = cur1.next;
    			cur2 = cur2.next;
    		}
    		return cur1;
    	} else { // 两个链表在环外没有相交
    		cur1 = loop1.next;
    		while (cur1 != loop1) { 
    			if (cur1 == loop2) { // cur1在环内转一圈,如果在环内与loop2相交,则返回loop1.
    				return loop1;
    			}
    			cur1 = cur1.next;
    		}
            // cur1在环内没有与loop2相遇,说明没有相交
    		return null;
    	}
    }
    
    public static void main(String[] args) {
    	// 1->2->3->4->5->6->7->null
    	Node head1 = new Node(1);
    	head1.next = new Node(2);
    	head1.next.next = new Node(3);
    	head1.next.next.next = new Node(4);
    	head1.next.next.next.next = new Node(5);
    	head1.next.next.next.next.next = new Node(6);
    	head1.next.next.next.next.next.next = new Node(7);
    
    	// 0->9->8->6->7->null
    	Node head2 = new Node(0);
    	head2.next = new Node(9);
    	head2.next.next = new Node(8);
    	head2.next.next.next = head1.next.next.next.next.next; // 8->6
    	System.out.println(getIntersectNode(head1, head2).value);
    
    	// 1->2->3->4->5->6->7->4...
    	head1 = new Node(1);
    	head1.next = new Node(2);
    	head1.next.next = new Node(3);
    	head1.next.next.next = new Node(4);
    	head1.next.next.next.next = new Node(5);
    	head1.next.next.next.next.next = new Node(6);
    	head1.next.next.next.next.next.next = new Node(7);
    	head1.next.next.next.next.next.next = head1.next.next.next; // 7->4
    
    	// 0->9->8->2...
    	head2 = new Node(0);
    	head2.next = new Node(9);
    	head2.next.next = new Node(8);
    	head2.next.next.next = head1.next; // 8->2
    	System.out.println(getIntersectNode(head1, head2).value);
    
    	// 0->9->8->6->4->5->6..
    	head2 = new Node(0);
    	head2.next = new Node(9);
    	head2.next.next = new Node(8);
    	head2.next.next.next = head1.next.next.next.next.next; // 8->6
    	System.out.println(getIntersectNode(head1, head2).value);
    
    }
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164

    }

    栈:数据先进后出,犹如弹匣
    双向链表实现栈

    数组实现栈

    怎么用数组实现不超过固定大小的栈

    如何用队列结构实现栈结构

    队列

    队列:数据先进先出,好似排队

    双向链表实现队列

    数组实现队列

    如何用栈结构实现队列结构

    递归

    递归并不是玄学,递归底层是利用系统栈来实现的
    任何递归函数都一定可以改成非递归
    Master公式
    形如
    T(N) = a * T(N/b) + O(N^d)(其中的a、b、d都是常数)
    的递归函数,可以直接通过Master公式来确定时间复杂度
    如果 log(b,a) < d,复杂度为O(N^d)
    如果 log(b,a) > d,复杂度为O(N^log(b,a))
    如果 log(b,a) == d,复杂度为O(N^d * logN)

    有序表
    1)有序表在使用层面上可以理解为一种集合结构2)如果只有key,没有伴随数据value,可以使用TreeSet结构3)如果既有key,又有伴随数据value,可以使用TreeMap结构4)有无伴随数据,是TreeSet和TreeMap唯一的区别,底层的实际结构是一回事5)有序表把key按照顺序组织起来,而哈希表完全不组织
    6)红黑树、AVL树、size-balance-tree和跳表等都属于有序表结构,只是底层具体实现不同7)放入如果是基础类型,内部按值传递,内存占用就是这个东西的大小8)放入如果不是基础类型,内部按引用传递,内存占用是8字节9)不管是什么底层具体实现,只要是有序表,都有以下固定的基本功能和固定的时间复杂度
    有序表在使用时,比哈希表功能多,时间复杂度都是O(logN)

    哈希表
    1)哈希表在使用层面上可以理解为一种集合结构
    2)如果只有key,没有伴随数据value,可以使用HashSet结构
    3)如果既有key,又有伴随数据value,可以使用HashMap结构
    4)有无伴随数据,是HashMap和HashSet唯一的区别,实际结构是一回事
    5)使用哈希表增(put)、删(remove)、改(put)和查(get)的操作,可以认为时间复杂度为 O(1),但是常数时间比较大
    6)放入哈希表的东西,如果是基础类型,内部按值传递,内存占用是这个东西的大小
    7)放入哈希表的东西,如果不是基础类型,内部按引用传递,内存占用是8字节


    二叉树
    递归套路
    1)假设以X节点为头,假设可以向X左树和X右树要任何信息
    2)在上一步的假设下,讨论以X为头节点的树,得到答案的可能性(最重要)
    3)列出所有可能性后,确定到底需要向左树和右树要什么样的信息
    4)把左树信息和右树信息求全集,就是任何一棵子树都需要返回的信息S
    5)递归函数都返回S,每一棵子树都这么要求
    6)写代码,在代码中考虑如何把左树的信息和右树信息整合出整棵树的信息
    结构
    Class Node {
    V value;
    Node left;
    Node right;
    }
    先序、中序、后序遍历
    先序:任何子树的处理顺序都是,先头节点、再左子树、然后右子树
    中序:任何子树的处理顺序都是,先左子树、再头节点、然后右子树
    后序:任何子树的处理顺序都是,先左子树、再右子树、然后头节点
    递归遍历(先序,中序,后序)
    public class Code01_RecursiveTraversalBT {

    public static class Node {
    	public int value;
    	public Node left;
    	public Node right;
    
    	public Node(int v) {
    		value = v;
    	}
    }
    
    
    // 递归先序遍历
    public static void pre(Node head) {
    	if (head == null) {
    		return;
    	}
    	System.out.println(head.value);
    	pre(head.left);
    	pre(head.right);
    }
    
    // 递归中序遍历
    public static void in(Node head) {
    	if (head == null) {
    		return;
    	}
    	in(head.left);
    	System.out.println(head.value);
    	in(head.right);
    }
    
    // 递归后序遍历
    public static void pos(Node head) {
    	if (head == null) {
    		return;
    	}
    	pos(head.left);
    	pos(head.right);
    	System.out.println(head.value);
    }
    
    • 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

    }
    迭代方法的遍历(先序,中序,后序)
    public class Code02_UnRecursiveTraversalBT {

    public static class Node {
    	public int value;
    	public Node left;
    	public Node right;
    
    	public Node(int v) {
    		value = v;
    	}
    }
    
    // 迭代先序遍历
    public static void pre(Node head) {
    	System.out.print("pre-order: ");
    	if (head != null) {
    		Stack stack = new Stack();
    		stack.add(head);
    		while (!stack.isEmpty()) {
    			head = stack.pop();
    			System.out.print(head.value + " ");
    			if (head.right != null) {
    				stack.push(head.right);
    			}
    			if (head.left != null) {
    				stack.push(head.left);
    			}
    		}
    	}
    	System.out.println();
    }
    
    // 迭代中序遍历
    public static void in(Node head) {
    	System.out.print("in-order: ");
    	if (head != null) {
    		Stack stack = new Stack();
    		while (!stack.isEmpty() || head != null) {
    			if (head != null) {
    				stack.push(head);
    				head = head.left;
    			} else {
    				head = stack.pop();
    				System.out.print(head.value + " ");
    				head = head.right;
    			}
    		}
    	}
    	System.out.println();
    }
    
    // 迭代方式的后序遍历
    public static void pos1(Node head) {
    	System.out.print("pos-order: ");
    	if (head != null) {
    		Stack s1 = new Stack();
    		Stack s2 = new Stack();
    		s1.push(head);
    		while (!s1.isEmpty()) {
    			head = s1.pop();
    			s2.push(head);
    			if (head.left != null) {
    				s1.push(head.left);
    			}
    			if (head.right != null) {
    				s1.push(head.right);
    			}
    		}
    		while (!s2.isEmpty()) {
    			System.out.print(s2.pop().value + " ");
    		}
    	}
    	System.out.println();
    }
    
    // 迭代方式的后序遍历
    public static void pos2(Node h) {
    	System.out.print("pos-order: ");
    	if (h != null) {
    		Stack stack = new Stack();
    		stack.push(h);
    		Node c = null;
    		while (!stack.isEmpty()) {
    			c = stack.peek();
    			if (c.left != null && h != c.left && h != c.right) {
    				stack.push(c.left);
    			} else if (c.right != null && h != c.right) {
    				stack.push(c.right);
    			} else {
    				System.out.print(stack.pop().value + " ");
    				h = c;
    			}
    		}
    	}
    	System.out.println();
    }
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94

    }
    层次遍历

    public class Code03_LevelTraversalBT {

    public static class Node {
    	public int value;
    	public Node left;
    	public Node right;
    
    	public Node(int v) {
    		value = v;
    	}
    }
    
    public static void level(Node head) {
    	if (head == null) {
    		return;
    	}
    	Queue queue = new LinkedList<>();
    	queue.add(head);
    	while (!queue.isEmpty()) {
    		Node cur = queue.poll();
    		System.out.println(cur.value);
    		if (cur.left != null) {
    			queue.add(cur.left);
    		}
    		if (cur.right != null) {
    			queue.add(cur.right);
    		}
    	}
    }
    
    • 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

    }
    二叉树的序列化和反序列化
    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
      • 1
    • TreeNode left;
      
      • 1
    • TreeNode right;
      
      • 1
    • TreeNode(int x) { val = x; }
      
      • 1
    • }
      */
      public class Codec {

      // Encodes a tree to a single string.
      public String serialize(TreeNode root) {
      return rserialize(root, “”);
      }

      // Decodes your encoded data to tree.
      public TreeNode deserialize(String data) {
      String[] dataArray = data.split(“,”);
      LinkedList dataList = new LinkedList<>(Arrays.asList(dataArray));
      return rdeserialize(dataList);
      }

      public String rserialize(TreeNode root, String str) {
      // 如果节点为null,则加入None标志。
      if (root == null) {
      str += “None,”;
      } else {
      // 按照先序遍历的顺序添加到字符串中。
      str += String.valueOf(root.val) + “,”;
      str = rserialize(root.left, str);
      str = rserialize(root.right, str);
      }
      return str;
      }

      public TreeNode rdeserialize(List dataList) {
      if (dataList.get(0).equals(“None”)) {
      dataList.remove(0);
      return null;
      }
      TreeNode root = new TreeNode(Integer.valueOf(dataList.get(0)));
      dataList.remove(0);
      root.left = rdeserialize(dataList);
      root.right = rdeserialize(dataList);
      return root;
      }
      }

    二叉树的最大宽度
    public class Code06_TreeMaxWidth {

    public static class Node {
    	public int value;
    	public Node left;
    	public Node right;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    public static int maxWidthUseMap(Node head) {
    	if (head == null) {
    		return 0;
    	}
    	Queue queue = new LinkedList<>();
    	queue.add(head);
    	HashMap levelMap = new HashMap<>();
    	levelMap.put(head, 1);
    	int curLevel = 1;
    	int curLevelNodes = 0;
    	int max = 0;
    	while (!queue.isEmpty()) {
    		Node cur = queue.poll();
    		int curNodeLevel = levelMap.get(cur);
    		if (cur.left != null) {
    			levelMap.put(cur.left, curNodeLevel + 1);
    			queue.add(cur.left);
    		}
    		if (cur.right != null) {
    			levelMap.put(cur.right, curNodeLevel + 1);
    			queue.add(cur.right);
    		}
    		if (curNodeLevel == curLevel) {
    			curLevelNodes++;
    		} else {
    			max = Math.max(max, curLevelNodes);
    			curLevel++;
    			curLevelNodes = 1;
    		}
    	}
    	max = Math.max(max, curLevelNodes);
    	return max;
    }
    
    public static int maxWidthNoMap(Node head) {
    	if (head == null) {
    		return 0;
    	}
    	Queue queue = new LinkedList<>();
    	queue.add(head);
    	Node curEnd = head;
    	Node nextEnd = null;
    	int max = 0;
    	int curLevelNodes = 0;
    	while (!queue.isEmpty()) {
    		Node cur = queue.poll();
    		if (cur.left != null) {
    			queue.add(cur.left);
    			nextEnd = cur.left;
    		}
    		if (cur.right != null) {
    			queue.add(cur.right);
    			nextEnd = cur.right;
    		}
    		curLevelNodes++;
    		if (cur == curEnd) {
    			max = Math.max(max, curLevelNodes);
    			curLevelNodes = 0;
    			curEnd = nextEnd;
    		}
    	}
    	return max;
    }
    
    • 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

    }
    二叉树的后继节点

    public class Code07_SuccessorNode {

    public static class Node {
    	public int value;
    	public Node left;
    	public Node right;
    	public Node parent;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    public static Node getSuccessorNode(Node node) {
    	if (node == null) {
    		return node;
    	}
    	if (node.right != null) {
            // 右树的最左节点
    		return getLeftMost(node.right);
    	} else { // 无右子树
    		Node parent = node.parent;
    		while (parent != null && parent.left != node) { // 当前节点是其父亲节点右孩子
    			node = parent;
    			parent = node.parent;
    		}
    		return parent;
    	}
    }
    
    public static Node getLeftMost(Node node) {
    	if (node == null) {
    		return node;
    	}
    	while (node.left != null) {
    		node = node.left;
    	}
    	return node;
    }
    
    public static void main(String[] args) {
    	Node head = new Node(6);
    	head.parent = null;
    	head.left = new Node(3);
    	head.left.parent = head;
    	head.left.left = new Node(1);
    	head.left.left.parent = head.left;
    	head.left.left.right = new Node(2);
    	head.left.left.right.parent = head.left.left;
    	head.left.right = new Node(4);
    	head.left.right.parent = head.left;
    	head.left.right.right = new Node(5);
    	head.left.right.right.parent = head.left.right;
    	head.right = new Node(9);
    	head.right.parent = head;
    	head.right.left = new Node(8);
    	head.right.left.parent = head.right;
    	head.right.left.left = new Node(7);
    	head.right.left.left.parent = head.right.left;
    	head.right.right = new Node(10);
    	head.right.right.parent = head.right;
    
    	Node test = head.left.left;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.left.left.right;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.left;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.left.right;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.left.right.right;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.right.left.left;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.right.left;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.right;
    	System.out.println(test.value + " next: " + getSuccessorNode(test).value);
    	test = head.right.right; // 10's next is null
    	System.out.println(test.value + " next: " + getSuccessorNode(test));
    }
    
    • 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

    }
    二叉树是否是平衡二叉树
    每一个子树的左树和右树的高度差不超过1.
    /**

    • Definition for a binary tree node.

    • public class TreeNode {

    • int val;
      
      • 1
    • TreeNode left;
      
      • 1
    • TreeNode right;
      
      • 1
    • TreeNode() {}
      
      • 1
    • TreeNode(int val) { this.val = val; }
      
      • 1
    • TreeNode(int val, TreeNode left, TreeNode right) {
      
      • 1
    •     this.val = val;
      
      • 1
    •     this.left = left;
      
      • 1
    •     this.right = right;
      
      • 1
    • }
      
      • 1
    • }
      */
      class Solution {
      public boolean isBalanced(TreeNode root) {
      boolean[] ans = new boolean[1];
      ans[0] = true;
      process(root, ans);
      return ans[0];
      }

      public int process(TreeNode root, boolean[] ans) {
      if (!ans[0] || root == null) {
      return -1;
      }
      int leftHeight = process(root.left, ans);
      int rightHeight = process(root.right, ans);
      // 只要在一个节点,他的左树和右树的高度相差超过1,则返回false。否则返回true
      if (Math.abs(leftHeight - rightHeight) > 1) {
      ans[0] = false;
      }
      return Math.max(leftHeight, rightHeight) + 1;
      }
      }
      二叉树上的最远距离
      给定一棵二叉树的头节点head,任何两个节点之间都存在距离,返回整棵二叉树的最大距离
      package class08;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.HashSet;

    public class Code08_MaxDistance {

    public static class Node {
    	public int value;
    	public Node left;
    	public Node right;
    
    	public Node(int data) {
    		this.value = data;
    	}
    }
    
    public static int maxDistance1(Node head) {
    	if (head == null) {
    		return 0;
    	}
    	ArrayList arr = getPrelist(head);
    	HashMap parentMap = getParentMap(head);
    	int max = 0;
    	for (int i = 0; i < arr.size(); i++) {
    		for (int j = i; j < arr.size(); j++) {
    			max = Math.max(max, distance(parentMap, arr.get(i), arr.get(j)));
    		}
    	}
    	return max;
    }
    
    public static ArrayList getPrelist(Node head) {
    	ArrayList arr = new ArrayList<>();
    	fillPrelist(head, arr);
    	return arr;
    }
    
    public static void fillPrelist(Node head, ArrayList arr) {
    	if (head == null) {
    		return;
    	}
    	arr.add(head);
    	fillPrelist(head.left, arr);
    	fillPrelist(head.right, arr);
    }
    
    public static HashMap getParentMap(Node head) {
    	HashMap map = new HashMap<>();
    	map.put(head, null);
    	fillParentMap(head, map);
    	return map;
    }
    
    public static void fillParentMap(Node head, HashMap parentMap) {
    	if (head.left != null) {
    		parentMap.put(head.left, head);
    		fillParentMap(head.left, parentMap);
    	}
    	if (head.right != null) {
    		parentMap.put(head.right, head);
    		fillParentMap(head.right, parentMap);
    	}
    }
    
    public static int distance(HashMap parentMap, Node o1, Node o2) {
    	HashSet o1Set = new HashSet<>();
    	Node cur = o1;
    	o1Set.add(cur);
    	while (parentMap.get(cur) != null) {
    		cur = parentMap.get(cur);
    		o1Set.add(cur);
    	}
    	cur = o2;
    	while (!o1Set.contains(cur)) {
    		cur = parentMap.get(cur);
    	}
    	Node lowestAncestor = cur;
    	cur = o1;
    	int distance1 = 1;
    	while (cur != lowestAncestor) {
    		cur = parentMap.get(cur);
    		distance1++;
    	}
    	cur = o2;
    	int distance2 = 1;
    	while (cur != lowestAncestor) {
    		cur = parentMap.get(cur);
    		distance2++;
    	}
    	return distance1 + distance2 - 1;
    }
    
    public static int maxDistance2(Node head) {
    	return process(head).maxDistance;
    }
    
    public static class Info {
    	public int maxDistance;
    	public int height;
    
    	public Info(int dis, int h) {
    		maxDistance = dis;
    		height = h;
    	}
    }
    
    public static Info process(Node head) {
    	if (head == null) {
    		return new Info(0, 0);
    	}
    	Info leftInfo = process(head.left);
    	Info rightInfo = process(head.right);
    	int height = Math.max(leftInfo.height, rightInfo.height) + 1;
    	int maxDistance = Math.max(Math.max(leftInfo.maxDistance, rightInfo.maxDistance),
    			leftInfo.height + rightInfo.height + 1);
    	return new Info(maxDistance, height);
    }
    
    // for test
    public static Node generateRandomBST(int maxLevel, int maxValue) {
    	return generate(1, maxLevel, maxValue);
    }
    
    // for test
    public static Node generate(int level, int maxLevel, int maxValue) {
    	if (level > maxLevel || Math.random() < 0.5) {
    		return null;
    	}
    	Node head = new Node((int) (Math.random() * maxValue));
    	head.left = generate(level + 1, maxLevel, maxValue);
    	head.right = generate(level + 1, maxLevel, maxValue);
    	return head;
    }
    
    public static void main(String[] args) {
    	int maxLevel = 4;
    	int maxValue = 100;
    	int testTimes = 1000000;
    	for (int i = 0; i < testTimes; i++) {
    		Node head = generateRandomBST(maxLevel, maxValue);
    		if (maxDistance1(head) != maxDistance2(head)) {
    			System.out.println("Oops!");
    		}
    	}
    	System.out.println("finish!");
    }
    
    • 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
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140

    }

    前缀树

    贪心算法
    1)最自然智慧的算法
    2)用一种局部最功利的标准,总是做出在当前看来是最好的选择
    3)难点在于证明局部最功利的标准可以得到全局最优解
    4)对于贪心算法的学习主要以增加阅历和经验为主
    贪心算法的解题套路
    1,实现一个不依靠贪心策略的解法X,可以用最暴力的尝试
    2,脑补出贪心策略A、贪心策略B、贪心策略C…
    3,用解法X和对数器,用实验的方式得知哪个贪心策略正确
    4,不要去纠结贪心策略的证明

    并查集

    动态规划

  • 相关阅读:
    VMware虚拟机三种网络模式设置 - Bridged(桥接模式)
    【生物技术】专业与JAVA开发10年之缘
    css中的z-index是什么
    Leecode DAY16: 二叉树的最大深度 and 二叉树的最小深度 and 完全二叉树的节点个数
    Python实现双X轴双Y轴绘图
    vxe-table表格校验失败后保持可以编辑状态
    C#中Semaphore 和 CountdownEvent 的使用总结
    【论文阅读】社交网络传播最大化问题-02
    基于docker创建mysql容器
    栈实现对称括号判断(c++)
  • 原文地址:https://blog.csdn.net/weixin_49756466/article/details/126168575