当前位置:网站首页>排序链表(归并排序)
排序链表(归并排序)
2022-07-01 03:13:00 【热心市民薛先生】
本题要求在 O(n log n) 时间复杂度和常数级空间复杂度下。排序算法中,只有快排、堆和归并排序时间复杂度可以满足要求,但是快排时间复杂度不稳定而且空间复杂度不是常数,堆不适合链表,所以要想到归并排序
public ListNode sortList(ListNode head) {
return mergeSort(head,null);
}
//递归分开阶段
public ListNode mergeSort(ListNode head,ListNode tail){
if(head == null) return head;
当只剩下两个结点时,直接断开,否则会一直递归死循环
if(head.next == tail){
head.next = null;
return head;
}
快慢指针,当快指针走到尾结点,慢指针会走到中间结点。
ListNode fast = head;
ListNode slow = head;
while(fast != tail){
slow = slow.next;
fast = fast.next;
if(fast != tail) fast = fast.next;
}
记录中间结点,然后递归
ListNode mid = slow;
递归头结点到中间结点
ListNode sort1 = mergeSort(head,mid);
递归中间结点到尾结点
注意此处不能像归并排序一样从中间的下一个开始
ListNode sort2 = mergeSort(mid,tail);
合并节阶段
ListNode res = merge(sort1,sort2);
return res;
}
//合并阶段
public ListNode merge(ListNode headA,ListNode headB){
建立一个链表头结点
ListNode dummy = new ListNode();
临时节点,记录链表的末尾位置
ListNode temp = dummy;
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA != null && tempB != null){
把节点值较小的放到前面
if(tempA.val < tempB.val){
temp.next = tempA;
tempA = tempA.next;
}else{
temp.next = tempB;
tempB = tempB.next;
}
链表指针后移
temp = temp.next;
}
当A不为空,说明B已经走完,直接把A剩下的部分加入链表末尾
if(tempA != null) temp.next = tempA;
当B不为空时同理
if(tempB != null) temp.next = tempB;
返回新建的链表
return dummy.next;
}
空间复杂度 log n
边栏推荐
- 打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
- Huawei operator level router configuration example | configuration static VPLS example
- Subnet division and subnet summary
- JUC learning
- JS日常开发小技巧(持续更新)
- Detailed list of errors related to twincat3 ads of Beifu
- 【机器学习】向量化计算 -- 机器学习路上必经路
- 终极套娃 2.0 | 云原生交付的封装
- 性能测试常见面试题
- HTB-Lame
猜你喜欢

Design practice of current limiting components

Ctfshow blasting WP

Huawei operator level router configuration example | configuration static VPLS example

Elk elegant management server log

实战 ELK 优雅管理服务器日志

C语言多线程编程入门学习笔记

Latest interface automation interview questions

STM32 - DS18B20 temperature sampling of first-line protocol

Completely solve the lost connection to MySQL server at 'reading initial communication packet

The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
随机推荐
Hal library setting STM32 interrupt
[QT] add knowledge supplement of third-party database
8 pits of redis distributed lock
POI exports excel and displays hierarchically according to parent-child nodes
Basic concepts of database
Edge Drawing: A combined real-time edge and segment detector 翻译
Druid监控统计数据源
咱就是说 随便整几千个表情包为我所用一下
mybati sql 语句打印
【小程序项目开发-- 京东商城】uni-app之首页商品楼层
Feign远程调用和Getaway网关
Lavaweb [first understanding the solution of subsequent problems]
Multithreaded printing
[reading notes] copywriting realization -- four golden steps for writing effective copywriting
ES6解构语法详解
Chapter 03_ User and authority management
【EXSI】主机间传输文件
E15 solution for cx5120 controlling Huichuan is620n servo error
POI导出excel,按照父子节点进行分级显示
MySQL index --01--- design principle of index