当前位置:网站首页>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. !!!
边栏推荐
- 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!
- 微信小程序 - 实现获取手机验证码倒计时 60 秒(手机号+验证码登录功能)
- 【c语言】基础篇学习笔记
- 【leetcode】34. Find the first and last positions of elements in a sorted array
- 二叉樹解題(二)
- Wechat applet JWT login issue token
- C language practice - number guessing game
- Document declaration and character encoding
- Pytorch-Yolov5從0運行Bug解决:
- Microsoft Research Institute's new book "Fundamentals of data science", 479 Pages pdf
猜你喜欢

【c语言】基础篇学习笔记

Research on the security of ognl and El expressions and memory horse

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

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

Mysql表insert中文变?号的问题解决办法

Installation and use of blue lake

Its appearance makes competitors tremble. Interpretation of Sony vision-s 02 products

C language practice - binary search (half search)

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

BGP experiment the next day
随机推荐
The confusion I encountered when learning stm32
Keil compilation code of CY7C68013A
Federal learning: dividing non IID samples according to Dirichlet distribution
[JS -- map string]
Ognl和EL表达式以及内存马的安全研究
Pytorch-Yolov5從0運行Bug解决:
Www2022 | know your way back: self training method of graph neural network under distribution and migration
Hand tear - sort
Deep understanding of lambda expressions
60后关机程序
Thinkphp6 limit interface access frequency
Sword finger offer II 006 Sort the sum of two numbers in the array
Spring moves are coming. Watch the gods fight
10 minutes to understand CMS garbage collector in JVM
My first experience of shadowless cloud computer
Force buckle 540 A single element in an ordered array
CorelDRAW Graphics Suite2022免费图形设计软件
千亿市场规模医疗美容行业的水究竟有多浑?
Li Kou interview question 02.08 Loop detection
WiFi 5GHz frequency