文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
题目描述:
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
java实现方法1:
/**
* 对链表进行排序
*
* @param head 节点head
* @return listNode节点
*/
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode lastNode = getLastNode(head);
return merge(sortList(head), sortList(lastNode));
}
/**
* 获取下半部分节点
*
* @param node 节点
* @return 后部分节点
*/
private ListNode getLastNode(ListNode node) {
ListNode fast = node;
ListNode slow = node;
ListNode breakN = node;
while (fast != null && fast.next != null) {
fast = fast.next.next;
breakN = slow;
slow = slow.next;
}
breakN.next = null;
return slow;
}
/**
* 合并两个链表
*
* @param l1 链表l1
* @param l2 链表l2
* @return 合并后链表
*/
private ListNode merge(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val <= l2.val) {
l1.next = merge(l1.next, l2);
return l1;
} else {
l2.next = merge(l1, l2.next);
return l2;
}
}
时间复杂度:O(n.logn)
空间复杂度:O(1)
Python实现方法1:
def sort_list(self, head: ListNode) -> ListNode:
'''
对链表进行排序
Args:
head: 节点
Returns:
链表
'''
if not head or not head.next:
return head
last_node = self.get_last_node(head)
l1 = self.sort_list(head)
l2 = self.sort_list(last_node)
return self.merge(l1, l2)
def get_last_node(self, node: ListNode) -> ListNode:
'''
获取后部分节点
Args:
node: node节点
Returns:
最后部分节点
'''
fast = node
slow = node
break_node = node
while fast and fast.next:
fast = fast.next.next
break_node = slow
slow = slow.next
break_node.next = None
return slow
def merge(self, l1: ListNode, l2: ListNode) -> ListNode:
'''
合并两个节点
Args:
l1: l1链表
l2: l2链表
Returns:
合并的链表
'''
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
l1.next = self.merge(l1.next, l2)
return l1
else:
l2.next = self.merge(l1, l2.next)
return l2
时间复杂度:O(n.logn)
空间复杂度:O(1)