当前位置:网站首页>Leetcode merge sort linked list
Leetcode merge sort linked list
2022-07-02 04:29:00 【Master_ hl】
Title Description
Sample analysis

Subject requirements
The time complexity is O(N*logN), At this time complexity, there are only three : Stack row 、 Quick line up 、 Merge sort , Quickly arrange for the worst case , yes O(N^2), Heap arrangement is not suitable for the sorting of linked lists , So it's only left to merge and sort .
Method 1 : From the top down ( recursive )
Top down approach , That is to split the linked list into two parts in the process of handing it out , Until only the last two nodes are left, it starts to merge back , When I come back , The left and right sequence segments have been ordered respectively , So the merging process is to merge two ordered sequence segments . But it still can't meet the requirements of completing this problem , Here is just a recursive idea , The idea of iteration will be given later .
Code implementation
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode slow = head;
ListNode fast = head.next;
// Speed pointer to split the linked list
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode midR = slow.next;
slow.next = null;// Empty the intermediate node is the next recursion return Necessary conditions
ListNode left = sortList(head);
ListNode right = sortList(midR);
// Merge
ListNode newHead = new ListNode(0);
ListNode prev = newHead;;
while(left != null && right != null) {
if(left.val <= right.val) {
prev.next = left;
left = left.next;
} else {
prev.next = right;
right = right.next;
}
prev = prev.next;
}
// Come here , Two ordered sequences , One is empty , One is not empty , Connect what is not empty to prev Behind
prev.next = (left != null ? left : right);
return newHead.next;
}Drawing analysis

The above figure analyzes the process of distributing and handing out the left half ,2 and 5 After merging, it becomes an ordered sequence segment , and midR On this side is a single ordered sequence segment with only one node , So it confirms the previous explanation .
Complexity analysis
- Time complexity :O(N*logN) , Is the time complexity of merging and sorting .
- Spatial complexity :O(logN), The merging of each layer uses auxiliary nodes , So spatial complexity is the height of the tree .
Method 2 : From the bottom up ( iteration )
Why can't we achieve constant space complexity from top to bottom , Because every recursion , It is necessary to open up an auxiliary stack space , And first execute the left , The right side has not been implemented , So stack space is not recycled , It will inevitably lead to higher spatial complexity than iteration . The way of iteration is not to operate the whole linked list first like recursion , Further subdivide , It's in order first , Four more four orderly ..., Finally, when subLen = Half the length of the linked list , After executing this cycle , It's all in order .
Code implementation
public ListNode sortList(ListNode head) {
if (head == null) {
return head;
}
int len = 0;
ListNode node = head;
while (node != null) {
len++;
node = node.next;
}
ListNode newHead = new ListNode(0, head);
// Each cycle keeps doubling the left and right sequences
for (int subLen = 1; subLen < len; subLen <<= 1) {
ListNode prev = newHead;
ListNode cur = newHead.next;
while (cur != null) {
ListNode head1 = cur;
// Move to the tail of the left subsequence
for (int i = 1; i < subLen && cur.next != null; i++) {
cur = cur.next;
}
ListNode head2 = cur.next;
// Division
cur.next = null;
cur = head2;
// Move to the tail of the right subsequence
for (int i = 1; i < subLen && cur != null && cur.next != null; i++) {
cur = cur.next;
}
// use next Record the head of the left sequence in the two sequences to be merged next time
ListNode next = null;
if (cur != null && cur.next != null) {
next = cur.next;
cur.next = null;
}
ListNode merged = merge(head1, head2);
// String the merged sequence after the auxiliary node
prev.next = merged;
while (prev.next != null) {
prev = prev.next;
}
cur = next;
}Drawing analysis

The difference between iteration and recursion can be clearly seen from the figure , It also confirms the above-mentioned two by two order , Four more four orderly , When subLen = 1/2 len When , After executing this cycle, it will be all in order . And iteration really opens up a constant stack space .
Complexity analysis
- Time complexity : O(N*logN)
- Spatial complexity : O(1)
This is the end of this article. !!!
边栏推荐
- C language practice - binary search (half search)
- Pytoch --- use pytoch to realize u-net semantic segmentation
- Shenzhen will speed up the cultivation of ecology to build a global "Hongmeng Oula city", with a maximum subsidy of 10million yuan for excellent projects
- Bitmap principle code record
- C语言猜数字游戏
- June book news | 9 new books are listed, with a strong lineup and eyes closed!
- 阿里云polkit pkexec 本地提权漏洞
- Www2022 | know your way back: self training method of graph neural network under distribution and migration
- IDEA xml中sql没提示,且方言设置没用。
- 深圳打造全球“鸿蒙欧拉之城”将加快培育生态,优秀项目最高资助 1000 万元
猜你喜欢

Ognl和EL表达式以及内存马的安全研究

Www2022 | know your way back: self training method of graph neural network under distribution and migration

Document declaration and character encoding

Deeply understand the concepts of synchronization and asynchrony, blocking and non blocking, parallel and serial

Exposure X8 Standard Version picture post filter PS, LR and other software plug-ins

Installation and use of blue lake

Play with concurrency: what's the use of interruptedexception?

藍湖的安裝及使用

Sword finger offer II 006 Sort the sum of two numbers in the array

Lei Jun wrote a blog when he was a programmer. It's awesome
随机推荐
One step implementation of yolox helmet detection (combined with oak intelligent depth camera)
万卷共知,一书一页总关情,TVP读书会带你突围阅读迷障!
How muddy is the water in the medical beauty industry with a market scale of 100 billion?
初识P4语言
[JS -- map string]
LCM of Spreadtrum platform rotates 180 °
【c语言】动态规划---入门到起立
60后关机程序
The difference between vectorresize and reverse.
uni-app - 实现获取手机验证码倒计时 60 秒(手机号+验证码登录功能)
Pytorch yolov5 exécute la résolution de bogues à partir de 0:
Which insurance company has a better product of anti-cancer insurance?
阿里云polkit pkexec 本地提权漏洞
深圳打造全球“鸿蒙欧拉之城”将加快培育生态,优秀项目最高资助 1000 万元
Ten thousand volumes are known to all, and one page of a book is always relevant. TVP reading club will take you through the reading puzzle!
Research on the security of ognl and El expressions and memory horse
[graduation season · advanced technology Er] young people have dreams, why are they afraid of hesitation
Binary tree problem solving (2)
LeetCode-归并排序链表
[C language] basic learning notes