【LeetCode】148. Sort List 排序链表(Medium)(JAVA)
题目地址: https://leetcode.com/problems/sort-list/
题目描述:
Given the head of a linked list, return the list after sorting it in ascending order.
Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is in the range [0, 5 * 10^4].
- -10^5 <= Node.val <= 10^5
题目大意
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
- 你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
解题方法
插入排序
- 根据采用插入排序的方法,对链表进行排序,时间复杂度 O(n^2)
- 插入排序:找到 A 节点,A.val < cur.val <= A.next.val,然后插入在 A 节点后面即可
- 不断循环往排序过的链表里插入节点即可
class Solution {
public ListNode sortList(ListNode head) {
ListNode res = null;
while (head != null) {
ListNode cur = head;
head = head.next;
cur.next = null;
res = insert(res, cur);
}
return res;
}
public ListNode insert(ListNode head, ListNode node) {
if (head == null) return node;
if (head.val >= node.val) {
node.next = head;
return node;
}
ListNode res = head;
while (head.next != null && head.next.val < node.val) {
head = head.next;
}
ListNode next = head.next;
head.next = node;
node.next = next;
return res;
}
}
直接超时了: Time Limit Exceeded
归并排序
- 题目要求 O(nlogn) 的时间复杂度,肯定要有一个二分过程,所以采用归并排序,一分为二,再合并
- 一分为二:关键是找出中间节点,采用快慢指针的方式
- 合并排序
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode mid = getMid(head);
ListNode node2 = mid.next;
mid.next = null;
return merge(sortList(head), sortList(node2));
}
public ListNode merge(ListNode node1, ListNode node2) {
ListNode res = new ListNode();
ListNode pre = res;
while (node1 != null || node2 != null) {
ListNode cur = null;
if (node1 == null) {
cur = node2;
node2 = node2.next;
} else if (node2 == null) {
cur = node1;
node1 = node1.next;
} else if (node1.val < node2.val) {
cur = node1;
node1 = node1.next;
} else {
cur = node2;
node2 = node2.next;
}
cur.next = null;
pre.next = cur;
pre = cur;
}
return res.next;
}
public ListNode getMid(ListNode head) {
if (head == null || head.next == null) return head;
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
执行耗时:8 ms,击败了27.46% 的Java用户
内存消耗:46.9 MB,击败了7.90% 的Java用户