zoukankan      html  css  js  c++  java
  • leetcode-hard-ListNode-148. Sort List

    mycode    97.37%

    如果用上一个题目中”参考“的方法,res中放节点而不是val,就会超时

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def sortList(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            res = []
            while head:
                res.append(head.val)
                head = head.next
            res.sort()
            
            dummy = head = ListNode(-1)
            for l in res:
                head.next = ListNode(l)
                head = head.next
            return dummy.next
                

    参考 

    二分法!!!!!!!

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def sortList(self, head):
            if not head or not head.next:
                return head
            slow, fast = head, head.next
            while fast and fast.next:
                slow = slow.next
                fast = fast.next.next
            second = slow.next
            slow.next = None
            first_half = self.sortList(head)
            second_half = self.sortList(second)
            return self.merge(first_half, second_half)
    
        def merge(self,l1, l2):
            if not l1 or not l2:
                return l2 or l1
            s, e = None, None
            while l1 and l2:
                if l1.val > l2.val:
                    if not s:
                        s = e = l2
                        l2 = l2.next
                    else:
                        e.next = l2
                        e = e.next
                        l2 = l2.next
                else:
                    if not s:
                        s = e = l1
                        l1 = l1.next
                    else:
                        e.next = l1
                        e = e.next
                        l1 = l1.next
            e.next = l1 or l2
            return s
  • 相关阅读:
    SDOI2020游记
    Git和GitHub详解
    P1251 餐巾计划问题
    P2824 [HEOI2016/TJOI2016]排序
    P3224 [HNOI2012]永无乡
    P3605 [USACO17JAN]Promotion Counting晋升者计数
    P4314 CPU监控
    P2939 [USACO09FEB]改造路Revamping Trails
    P4254 [JSOI2008]Blue Mary开公司
    P1772 [ZJOI2006]物流运输
  • 原文地址:https://www.cnblogs.com/rosyYY/p/11050165.html
Copyright © 2011-2022 走看看