zoukankan      html  css  js  c++  java
  • 排序链表

    148. 排序链表

    难度 ⭐⭐

    O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

    示例 1:

    输入: 4->2->1->3
    输出: 1->2->3->4
    

    示例 2:

    输入: -1->5->3->4->0
    输出: -1->0->3->4->5
    

    思路

    (O(nlogn))时间复杂度,分而治之,使用归并排序,数组归并排序代码可以看这里

    • 分割(找到中间节点,使用快慢指针)
    • 合并

    coding

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def sortList(self, head: ListNode) -> ListNode:
            #递归退出条件
            if not head or not head.next:
                return head
            #找到中间节点
            mid = self.divide(head)
            temp = mid.next
            mid.next = None
            #递归 合并
            l = self.sortList(head)
            r = self.sortList(temp)
            return self.merge(l,r)
            
        def divide(self,head):
            #找到链表中间节点
            if not head or not head.next:
                return head
            slow,fast = head,head.next.next
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            return slow
        
        def merge(self,left,right):
            #合并链表
            new = ListNode(0)
            curr = new
            while left and right:
                if left.val <= right.val:
                    curr.next = left
                    left = left.next
                else:
                    curr.next = right
                    right = right.next
                curr = curr.next
                
            if left:
                curr.next = left 
            if right:
                curr.next = right
            
            return new.next
    
    
  • 相关阅读:
    前端UI框架
    Knowledge
    Microsoft SQL Server
    ASP.NET MVC
    将博客搬至CSDN
    python中的数据类型
    python基础知识
    接口和抽象类的区别
    面向对象的四大特征
    数据结构学习笔记
  • 原文地址:https://www.cnblogs.com/gongyanzh/p/12943862.html
Copyright © 2011-2022 走看看