【LeetCode笔记】148. 排序链表(Java、归并排序、快慢指针、双重递归)

题目描述

  • 难点在于时空复杂度的要求
    在这里插入图片描述

思路 & 代码

  • 转化成:归并排序 + 合并两个有序链表 即可
  • 利用快慢指针来拆分成两条链表
  • 注意:链表的拆分 & 连接
  • 时间复杂度O(n * logn),空间复杂度 O(1)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        // 1. 快慢指针分出前后两部分,递归
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        // 长度为2的情况特殊考虑
        if(slow.next == null){
            slow = head;
        }
        // 拆解,递归 O(logn)
        fast = sortList(slow.next);
        slow.next = null;
        slow = sortList(head);

        // 2. 返回值,进行合并(转化成合并链表)
        return mergeSortedList(slow, fast);
    }
    // 链表合并O(n)
    ListNode mergeSortedList(ListNode head1, ListNode head2){
        if(head1 == null){
            return head2;
        }
        if(head2 == null){
            return head1;
        }
        if(head1.val < head2.val){
            head1.next = mergeSortedList(head1.next, head2);
            return head1;
        }
        else{
            head2.next = mergeSortedList(head1, head2.next);
            return head2;
        }
    }
}

二刷

  • 好吧…记得思路是快慢指针 + 合并有序链表,但是具体咋写确实回想不起来= =
  • 其实就是两个函数:快慢指针二分链表 + 合并两个有序链表,双重递归!
class Solution {
    // 1. 快慢指针二分链表
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode slow = head, fast = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        // 两个的情况,避免无限循环
        if(slow.next == null) {
            slow = head;
        }
        fast = sortList(slow.next);
        slow.next = null;
        slow = sortList(head);
        return mergeSort(slow, fast);
    }
    // 2. 合并两个有序链表 O(n)、O(1)
    public ListNode mergeSort(ListNode headA, ListNode headB) {
        if(headB == null) {
            return headA;
        }
        if(headA == null) {
            return headB;
        }
        if(headA.val < headB.val) {
            headA.next = mergeSort(headA.next, headB);
            return headA;
        }
        else {
            headB.next = mergeSort(headA, headB.next);
            return headB;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值