Skip to content

递归算法

zhangpan edited this page Aug 20, 2021 · 4 revisions
/**
 * 递归法
 * 递归的递流程直接找到递归的最后一个节点,最后一个节点的next为null,返回自身,然后开始递归的归流程
 * 递归的归流程,从最后一个节点向上回溯,将最后一个节点的next指向倒数第二个节点,倒数第二个节点的next指向null
 * 以此回溯到第一个节点完成链表的反转
 */
public static ListNode reverseLink2(ListNode head) {
    // head == null这个条件一定要判断啊!!!!
    if (head == null || head.next == null) {
        return head;
    }
    // 返回最后一个节点
    ListNode lastNode = reverseLink2(head.next);
    head.next.next = head;
    head.next = null;
    return lastNode;
}
public static ListNode cursor;

public static ListNode reverseLink(ListNode head, int n) {
    if (n == 1) {
        cursor = head.next;
        return head;
    }
    ListNode lastNode = reverseLink(head.next, n - 1);
    head.next.next = head;
    head.next = cursor;
    return lastNode;
}
public ListNode reverseBetween(ListNode head, int left, int right) {
    if (head == null || head.next == null) {
        return head;
    }
    return reverse(head, left, right);
}

private ListNode reverse(ListNode head, int left, int right) {
    if (left == 1) {
        return LeetCode92$.reverseLink(head, right);
    }
    head.next = reverse(head.next, left - 1, right - 1);
    return head;
}
/**
 * 递归法
 */
public ListNode mergeTwoList2(ListNode l1, ListNode l2) {
    if (l1 == null) {
        return l2;
    } else if (l2 == null) {
        return l1;
    } else {
        if (l1.val < l2.val) {
            l1.next = mergeTwoList2(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoList2(l1, l2.next);
            return l2;
        }
    }
}

快速排序

/**
 * 快速排序
 * <p>
 * 核心的思路是取第一个元素(或者最后一个元素)作为分界点,把整个数组分成左右两侧,左边的元素小于或者等于分界点元素,
 * 而右边的元素大于分界点元素,然后把分界点移到中间位置,对左右子数组分别进行递归,最后就能得到一个排序完成的数组。
 * 当子数组只有一个或者没有元素的时候就结束这个递归过程。
 */
public static void quickSort(int[] nums, int left, int right) {
    if (left > right) return;
    int key = nums[left];
    int l = left;
    int r = right;
    while (l < r) {
        while (nums[r] >= key && l < r)
            r--;
        while (nums[l] <= key && l < r)
            l++;
        if (l < r)
            swap(nums, r, l);
    }

    nums[left] = nums[r];
    nums[r] = key;

    quickSort(nums, left, r - 1);
    quickSort(nums, r + 1, right);
}

公众号:玩转安卓Dev

Java基础

面向对象与Java基础知识

Java集合框架

JVM

多线程与并发

设计模式

Kotlin

Android

Android基础知识

Android消息机制

Framework

View事件分发机制

Android屏幕刷新机制

View的绘制流程

Activity启动

性能优化

Jetpack&系统View

第三方框架实现原理

计算机网络

算法

其它

Clone this wiki locally