leetcode148 sort list

来源:互联网 发布:电脑摇号软件 编辑:程序博客网 时间:2024/06/06 06:46
# 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
        """
        h=head
        vals=[]
        while h!=None:
            vals.append(h.val) 
            h=h.next
        vals.sort()
        h1=head
        count=0
        while h1!=None:
            h1.val=vals[count]
            count+=1
            h1=h1.next

        return head

o(n)


# 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
        """
        h=head
        vals=[]
        while h!=None:
            vals.append(h.val) 
            h=h.next
        vals.sort()
        h1=head
        for val in vals:
            h1.val=val
            h1=h1.next
        return head


参考https://discuss.leetcode.com/topic/34054/python-solution-beats-99-08-but-using-o-n-space

0 0
原创粉丝点击