当前位置:网站首页>Sort linked list (merge sort)
Sort linked list (merge sort)
2022-07-01 03:36:00 【Enthusiastic citizen Mr. Xue】
This question requires that O(n log n) Under time complexity and constant space complexity . In the sorting algorithm , Only quick platoon 、 The time complexity of heap and merge sort can meet the requirements , But the time complexity of fast scheduling is unstable and the space complexity is not constant , Heap is not suitable for linked list , So think about merging and sorting
public ListNode sortList(ListNode head) {
return mergeSort(head,null);
}
// Recursively separate stages
public ListNode mergeSort(ListNode head,ListNode tail){
if(head == null) return head;
When there are only two nodes left , Directly disconnect , Otherwise, it will be recursive forever
if(head.next == tail){
head.next = null;
return head;
}
Speed pointer , When the fast pointer reaches the tail node , The slow pointer will go to the middle node .
ListNode fast = head;
ListNode slow = head;
while(fast != tail){
slow = slow.next;
fast = fast.next;
if(fast != tail) fast = fast.next;
}
Record intermediate nodes , Then a recursive
ListNode mid = slow;
Recursion from head node to intermediate node
ListNode sort1 = mergeSort(head,mid);
Recursion from intermediate node to tail node
Note that you cannot start from the next in the middle like merge sorting
ListNode sort2 = mergeSort(mid,tail);
Merge section stage
ListNode res = merge(sort1,sort2);
return res;
}
// Consolidation phase
public ListNode merge(ListNode headA,ListNode headB){
Create a chain header node
ListNode dummy = new ListNode();
Temporary node , Record the end position of the linked list
ListNode temp = dummy;
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA != null && tempB != null){
Put the smaller node value in front
if(tempA.val < tempB.val){
temp.next = tempA;
tempA = tempA.next;
}else{
temp.next = tempB;
tempB = tempB.next;
}
Linked list pointer backward
temp = temp.next;
}
When A Not empty , explain B It's over , Put... Directly A The rest is added to the end of the linked list
if(tempA != null) temp.next = tempA;
When B The same is true when it is not empty
if(tempB != null) temp.next = tempB;
Return to the new linked list
return dummy.next;
}
Spatial complexity log n
边栏推荐
- [deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st
- 在线公网安备案保姆级教程【伸手党福利】
- [深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
- ECMAScript 6.0
- 深度学习中的随机种子torch.manual_seed(number)、torch.cuda.manual_seed(number)
- shell脚本使用两个横杠接收外部参数
- Pytorch training deep learning network settings CUDA specified GPU visible
- 【伸手党福利】开发人员重装系统顺序
- TEC: Knowledge Graph Embedding with Triple Context
- FCN全卷积网络理解及代码实现(来自pytorch官方实现)
猜你喜欢

The method to measure the similarity of two vectors: cosine similarity, pytorch calculate cosine similarity: torch nn. CosineSimilarity(dim=1, eps=1e-08)

Nacos

Take you through a circuit board, from design to production (dry goods)

实现pow(x,n)函数

Basic concepts of database

Nacos

Appium自动化测试基础--补充:C/S架构和B/S架构说明

File upload and download
![[small sample segmentation] interpretation of the paper: prior guided feature enrichment network for fee shot segmentation](/img/b3/887d3fb64acbf3702814d32e2e6414.png)
[small sample segmentation] interpretation of the paper: prior guided feature enrichment network for fee shot segmentation

Hal library setting STM32 interrupt
随机推荐
Server rendering technology JSP
The combination of applet container technology and IOT
LeetCode 31下一个排列、LeetCode 64最小路径和、LeetCode 62不同路径、LeetCode 78子集、LeetCode 33搜索旋转排序数组(修改二分法)
[small sample segmentation] interpretation of the paper: prior guided feature enrichment network for fee shot segmentation
【读书笔记】《文案变现》——写出有效文案的四个黄金步骤
Pytest -- plug-in writing
数据交换 JSON
leetcode 1818 绝对值,排序,二分法,最大值
LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表
岭回归和lasso回归
Redis tutorial
[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st
Leetcode:829. 连续整数求和
Ultimate dolls 2.0 | encapsulation of cloud native delivery
Go tool cli for command line implementation
Learning notes for introduction to C language multithreaded programming
后台系统右边内容如何出现滚动条和解决双滚动条的问题
How to achieve 0 error (s) and 0 warning (s) in keil5
GCC usage, makefile summary
家居网购项目