当前位置:网站首页>排序链表(归并排序)
排序链表(归并排序)
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
边栏推荐
- 终极套娃 2.0 | 云原生交付的封装
- [us match preparation] complete introduction to word editing formula
- 第03章_用户与权限管理
- How to verify whether the contents of two files are the same
- Detailed list of errors related to twincat3 ads of Beifu
- Force buckle - sum of two numbers
- JS日常开发小技巧(持续更新)
- IEDA 右键源码文件菜单简介
- 调试定位导航遇到的问题总结
- Analyze datahub, a new generation metadata platform of 4.7K star
猜你喜欢
[QT] add knowledge supplement of third-party database
Const and the secret of pointers
[machine learning] vectorized computing -- a must on the way of machine learning
【小程序项目开发-- 京东商城】uni-app之首页商品楼层
Depth first traversal of C implementation Diagram -- non recursive code
STM32 - DS18B20 temperature sampling of first-line protocol
JUC learning
How the network is connected: Chapter 2 (Part 2) packet receiving and sending operations between IP and Ethernet
So easy deploy program to server
Huawei operator level router configuration example | configuration static VPLS example
随机推荐
Basic concepts of database
Analyze datahub, a new generation metadata platform of 4.7K star
Introduction and basic knowledge of machine learning
xxl-job使用指南
力扣-两数之和
Nacos
Mybati SQL statement printing
An article explaining the publisher subscriber model and the observer model
Ridge regression and lasso regression
mybati sql 语句打印
ES6解构语法详解
How to achieve 0 error (s) and 0 warning (s) in keil5
Force buckle - sum of two numbers
调试定位导航遇到的问题总结
gcc使用、Makefile总结
Mysql知识点
ctfshow爆破wp
multiple linear regression
Depth first traversal of C implementation Diagram -- non recursive code
限流组件设计实战