当前位置:网站首页>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. !!!
边栏推荐
- 记录一次Unity 2020.3.31f1的bug
- Thinkphp Kernel wo system source Commercial Open source multi - user + multi - Customer Service + SMS + email notification
- What methods should service define?
- Typescript practice for SAP ui5
- Common sense of cloud server security settings
- Its appearance makes competitors tremble. Interpretation of Sony vision-s 02 products
- Li Kou interview question 02.08 Loop detection
- Play with concurrency: draw a thread state transition diagram
- One step implementation of yolox helmet detection (combined with oak intelligent depth camera)
- Today's plan: February 15, 2022
猜你喜欢

My first experience of shadowless cloud computer

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

Thinkphp Kernel wo system source Commercial Open source multi - user + multi - Customer Service + SMS + email notification

Markdown编辑语法

Unit testing classic three questions: what, why, and how?

Websites that it people often visit

阿里云polkit pkexec 本地提权漏洞

Deep understanding of lambda expressions

Spring recruitment of Internet enterprises: Kwai meituan has expanded the most, and the annual salary of technical posts is up to nearly 400000

Dare to go out for an interview without learning some distributed technology?
随机推荐
There is no prompt for SQL in idea XML, and the dialect setting is useless.
CY7C68013A之keil编译代码
Fluent icon demo
Typescript practice for SAP ui5
BGP experiment the next day
Wechat applet calculates the distance between the two places
Read "the way to clean code" - function names should express their behavior
社交媒体搜索引擎优化及其重要性
Homework of the 16th week
UNET deployment based on deepstream
Www 2022 | rethinking the knowledge map completion of graph convolution network
LeetCode-对链表进行插入排序
Social media search engine optimization and its importance
Research on the security of ognl and El expressions and memory horse
【c语言】基础篇学习笔记
Wechat applet - realize the countdown of 60 seconds to obtain the mobile verification code (mobile number + verification code login function)
A summary of common interview questions in 2022, including 25 technology stacks, has helped me successfully get an offer from Tencent
记录一次Unity 2020.3.31f1的bug
Use a mask to restrict the input of the qlineedit control
藍湖的安裝及使用