当前位置:网站首页>[leetcode] linked list sorting (gradually increasing the space-time complexity)
[leetcode] linked list sorting (gradually increasing the space-time complexity)
2022-06-30 15:37:00 【Xiaozhu Xiaozhu will never admit defeat】
An interview question , List sorting .
List of articles
List sorting
1. Title Description
leetcode Topic link :148. Sort list
Advanced : You can O(n log n) Under time complexity and constant space complexity , Sort the linked list ?
2. Thought analysis
The time complexity of this problem is better than O(n2) Sort algorithm . The advanced problem of the subject is required to meet the requirements O(nlogn) Time complexity and O(1) Spatial complexity of , The time complexity is O(nlogn) The sorting algorithm includes merge sorting 、 Heap sort and quick sort ( The worst time complexity of quick sort is O(n2), One of the most suitable sorting algorithms for linked lists is merge sorting .
Method 1 : Heap sort
The simplest and direct way :
- The definition type is ListNode The smallest pile
- Building the heap : Linked list all node Into the heap
- Eject the top of the stack one by one node, That is, from small to large
- Time complexity O(nlogn), Spatial complexity O(n)
- This method is almost the same as the heap sorting of arrays , It's the easiest thing to do , It's not easy to make mistakes.
Method 2 : Top down merge sort
Optimize space complexity .
The process of merging and sorting the linked list from top to bottom is as follows .
- Find the midpoint of the list , With the midpoint as the boundary , Split the linked list into two sub linked lists . To find the midpoint of the linked list, you can use the fast and slow pointer , Every time the fast pointer moves 2 Step , Each time the slow pointer moves 1 Step , When the fast pointer reaches the end of the linked list , The linked list node pointed to by the slow pointer is the midpoint of the linked list .
- Sort the two sub linked lists separately .
- Merge the two sorted sub linked lists , Get the complete sorted linked list .
The above process can be implemented recursively . The termination condition of recursion is that the number of nodes in the linked list is less than or equal to 1, That is, when the linked list is empty or the linked list only contains 1 When a node , There is no need to split and sort the linked list .
Complexity analysis
- Time complexity :O(nlogn), among n It's the length of the list .
- Spatial complexity :O(logn), among n It's the length of the list . The space complexity mainly depends on the stack space of recursive calls .
Method 3 : Bottom up merge sort
Further optimize the space complexity .
Spatial complexity O(1). Start from a single node and merge into a multi segment ordered linked list ; Merge the multi segment ordered linked list in pairs , Until it is merged into a complete linked list .
3. Code implementation
Method 1 : Heap sort
class Solution {
public ListNode sortList(ListNode head) {
// Heap sort
PriorityQueue<ListNode> queue = new PriorityQueue<>((a, b) -> a.val - b.val); // Small cap pile
while (head != null) {
// Add all to the small top pile
queue.offer(head);
head = head.next;
}
// Out of pile , Assign a value to the new linked list
ListNode dumpy = new ListNode();
ListNode cur = dumpy;
while (queue.size() > 0) {
cur.next = queue.poll();
cur = cur.next;
}
cur.next = null;
return dumpy.next;
}
}
Method 2 : Top down merge sort
class Solution {
public ListNode sortList(ListNode head) {
// If the list is empty , Or just one node , Go straight back to , No sorting
if (head == null || head.next == null) return head;
// Fast and slow double pointer movement , Find intermediate nodes
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
// Find the middle node ,slow Node next Pointer to mid
ListNode mid = slow.next;
// Cut off the linked list
slow.next = null;
// Sort the left sub linked list
ListNode left = sortList(head);
// Sort right sub linked list
ListNode right = sortList(mid);
// Merge list
return merge(left, right);
}
public ListNode merge(ListNode left, ListNode right) {
ListNode head = new ListNode(0);
ListNode tmp = head;
while (left != null && right != null) {
if (left.val <= right.val) {
tmp.next = left;
left = left.next;
} else {
tmp.next = right;
right = right.next;
}
tmp = tmp.next;
}
if (left != null) {
tmp.next = left;
} else if (right != null) {
tmp.next = right;
}
return head.next;
}
}
边栏推荐
- Tetris source code (color version)
- 1062 talent and virtue (25 points)
- Text matching - [naacl 2022] GPL
- Matlab to find prime pairs within 100
- 4.6 floating point number
- 4.7 type() function query data type
- C. Registration system(map)
- Talk about why I started technical writing
- On which platform is it safer to buy Treasury reverse repo?
- 开源 STM32 USB-CAN项目
猜你喜欢
Xiao Sha's pain (thinking problem)
Single cycle CPU of the design group of West University of Technology
Super comprehensive redis distributed high availability solution: sentry mechanism
map reduce案例超详细讲解
What would you choose between architecture optimization and business iteration?
001 data type [basic]
消息队列十连问
Voice codec based on machine learning Agora silver: support high quality voice interaction at ultra-low bit rate
Three types of technical debt that programmers often encounter: code, data, and architecture
Infrastructure is code. What are you talking about?
随机推荐
FoxPro and I
1031 Hello world for u (20 points)
Examples of bubble sorting and matrix element screening in MATLAB
比亚迪越来越像华为?
1151 LCA in a binary tree (30 points)
What would you choose between architecture optimization and business iteration?
1131: genetic correlation
剑指 Offer II 080. 含有 k 个元素的组合 回溯
HD mechanical principle · classic dynamic drawing of mechanical design
How to do a good job in high concurrency system design? I have summarized three points
K - rochambau (joint search, enumeration)
4.5 integer
1066 root of AVL tree (25 points)
Voice codec based on machine learning Agora silver: support high quality voice interaction at ultra-low bit rate
Tetris source code (color version)
1027 colors in Mars (20 points)
A little idea about big experiment data
Chapter 2 installation and use of vscode editor
1107 social clusters (30 points)
Database connection to company database denied