LeetCode-148. 排序链表【链表 双指针 分治 排序 归并排序】

news/2024/5/17 16:16:18 标签: leetcode, 链表, 算法, 递归, 归并排序

LeetCode-148. 排序链表链表 双指针 分治 排序 归并排序

  • 题目描述:
  • 解题思路一:递归归并排序,两个关键点,找到中点mid和分割链表。前者通过快慢指针,后者通过指向None。即mid, slow.next = slow.next, None
  • 解题思路二:归并排序(从底至顶直接合并)非递归
  • 解题思路三:0

题目描述:

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

示例 1:
在这里插入图片描述
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
在这里插入图片描述
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:

输入:head = []
输出:[]

提示:

链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105

进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗

解题思路一:递归归并排序,两个关键点,找到中点mid和分割链表。前者通过快慢指针,后者通过指向None。即mid, slow.next = slow.next, None

然后对分割的链表再次进行递归分割,直到满足终止条件if not head or not head.next:
最后进行归并排序:空间复杂度:O(logn)
在这里插入图片描述

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next: # termination.
            return head
        slow, fast = head, head.next
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next
        mid, slow.next = slow.next, None # mid  奇数个节点找到中点右边,偶数个节点找到中心右边的节点。slow.next =  None 分割链表
        left, right = self.sortList(head), self.sortList(mid) # 递归分割
        h = res = ListNode(0)
        while left and right: # 归并排序
            if left.val < right.val:
                h.next, left = left, left.next
            else:
                h.next, right = right, right.next
            h = h.next
        h.next = left if left else right
        return res.next

时间复杂度:O(nlogn)
空间复杂度:O(logn)

解题思路二:归并排序(从底至顶直接合并)非递归

在这里插入图片描述

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        h, length, intv = head, 0, 1
        while h: h, length = h.next, length + 1
        res = ListNode(0)
        res.next = head
        # merge the list in different intv.
        while intv < length:
            pre, h = res, res.next
            while h:
                # get the two merge head `h1`, `h2`
                h1, i = h, intv
                while i and h: h, i = h.next, i - 1
                if i: break # no need to merge because the `h2` is None.
                h2, i = h, intv
                while i and h: h, i = h.next, i - 1
                c1, c2 = intv, intv - i # the `c2`: length of `h2` can be small than the `intv`.
                # merge the `h1` and `h2`.
                while c1 and c2:
                    if h1.val < h2.val: pre.next, h1, c1 = h1, h1.next, c1 - 1
                    else: pre.next, h2, c2 = h2, h2.next, c2 - 1
                    pre = pre.next
                pre.next = h1 if c1 else h2
                while c1 > 0 or c2 > 0: pre, c1, c2 = pre.next, c1 - 1, c2 - 1
                pre.next = h 
            intv *= 2
        return res.next

详见https://leetcode.cn/problems/sort-list/solutions/13728/sort-list-gui-bing-pai-xu-lian-biao-by-jyd
时间复杂度:O(nlogn)
空间复杂度:O(1)

解题思路三:0


时间复杂度:O(n)
空间复杂度:O(n)


http://www.niftyadmin.cn/n/5467647.html

相关文章

Win11电脑cpu温度过高怎么办呢

Win11电脑cpu温度过高怎么办呢&#xff1f;有时候我们感觉电脑发烫&#xff0c;担心电脑过烫会不会损坏。正常情况下&#xff0c;cpu的温度在45~65度之间&#xff0c;但不排除电脑同时开了太多软件&#xff0c;或者在玩吃鸡、英雄联盟等的大型游戏而导致温度超过85度。只要最高…

IPKISS ------ 导入 Lumerical S-matrix 仿真结果

IPKISS ------ 导入 Lumerical S-matrix 仿真结果 引言引言 这里给大家介绍一下如何使用 IPKISS 导入 Lumerical 中器件 S Matrix 的仿真结果。 import ipkiss3.all as i3 import matplotlib.pyplot as plt import numpy as nps_matrix = i3.device_sim.satrix1swep.from_tou…

MySQL两表联查之分组成绩第几问题

MySQL 数据库操作实践&#xff1a;两表联查之分组成绩第几问题 在本篇博客中&#xff0c;我将展示MySQL 从创建表、到插入数据&#xff0c;并进行一些复杂的查询操作。 1. 建立表格 首先&#xff0c;我们创建两个表&#xff1a;department&#xff08;部门&#xff09;和 em…

kind+tidb

官网介绍&#xff1a;在 Kubernetes 上快速上手 TiDB | PingCAP 文档中心 下面是具体细节&#xff1a; 一、安装 1.安装kind&#xff0c;一定要使用最新版本&#xff01;&#xff01;&#xff01; kind官网&#xff1a;kind – Quick Start curl -Lo ./kind https://kind.s…

Python大型数据集(GPU)可视化和Pillow解释性视觉推理及材料粒子凝聚

&#x1f3af;要点 P​y​t​ho​n​图像​处理Pillow​库​&#xff1a;&#x1f3af;打开图像、保存图像、保存期间的压缩方式、读取方法、创建缩略图、创建图像查看器。&#x1f3af;获取 RGB 值&#xff0c;从图像中获取颜色&#xff0c;更改像素颜色&#xff0c;转换为黑…

Nginx基础(02)

Nginx基础&#xff08;01&#xff09; 动态网站 : 在不同环境访问 , 网站内容有可能发生变化 **静态网站 : ** 在不同环境访问 , 网站内容不会发生变化 默认nginx仅可以处理静态数据&#xff0c;用户访问任何数据都是直接返回对应的文件&#xff0c;如果如果访问的是一个脚本的…

解决vue热加载卡顿缓慢

安装插件&#xff1a;babel-plugin-dynamic-import-node npm install babel-plugin-dynamic-import-node --save-dev配置babel.config.js文件 env: {development: {plugins: [dynamic-import-node]}}重启项目&#xff0c;完成

环境搭建 | Windows 11系统从0开始搭建SonarQube环境分析C sharp项目代码

1 安装&使用流程 JDK 17环境搭建Sonarqube 10.0安装PostgreSQL 12数据库安装配置MSBuild下载安装SonarScanner for MSBuild使用SonarQube分析C#代码并上传到服务器 注意&#xff1a;SonarQube环境搭建时对各个软件的版本都有要求&#xff0c;如果你不确定使用何版本&…