[LeetCode][Python3] 148. Sort List
2019. 4. 4. 01:25 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/sort-list/
My Solution :
# 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 head and head.next:
prev = slow = fast = head
while fast and fast.next:
prev = slow
slow = slow.next
fast = fast.next.next
prev.next = None
left = self.sortList(head)
right = self.sortList(slow)
return self.merge(left, right)
return head
def merge(self, left, right):
current = dummy = ListNode(0)
while left and right:
if left.val < right.val:
current.next = left
left = left.next
else:
current.next = right
right = right.next
current = current.next
current.next = left or right
return dummy.next
Comment :
문제에서 O(nlogn) time and O(1) space 를 요구했기 때문에 병합정렬을 활용해 풀어야 한다. 나는 처음에 해당 조건을 무시하고 그냥 아래와 같이 내장 sorted를 활용하였다. 속도는 내장 sorted가 훨씬 빠르게 동작한다.
My Solution 2 :
# 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:
return head
nodes = []
while head:
nodes.append(head)
head = head.next
nodes = sorted(nodes, key=lambda x: x.val)
for i in range(len(nodes)-1):
nodes[i].next = nodes[i+1]
nodes[-1].next = None
return nodes[0]
그리고 val만 뽑아서 정렬한 다음 ListNode의 next를 재배치 하는 대신 val을 직접 수정하면 조금 더 빠르다.
My Solution 3 :
# 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:
vals = []
curr = head
while curr:
vals.append(curr.val)
curr = curr.next
vals = sorted(vals)
i = 0
curr = head
while curr:
curr.val = vals[i]
i += 1
curr = curr.next
return head
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 227. Basic Calculator II (0) | 2019.04.09 |
---|---|
[LeetCode][Python3] 134. Gas Station (0) | 2019.04.08 |
[LeetCode][Python3] 23. Merge k Sorted Lists (0) | 2019.04.07 |
[LeetCode][Python3] 210. Course Schedule II (0) | 2019.04.05 |
[LeetCode][Python3] 139. Word Break (0) | 2019.04.03 |
[LeetCode][Python3] 56. Merge Intervals (0) | 2019.04.03 |
[LeetCode][Python3] 295. Find Median from Data Stream (0) | 2019.04.02 |
[LeetCode][Python3] 236. Lowest Common Ancestor of a Binary Tree (0) | 2019.04.01 |
최근에 달린 댓글 최근에 달린 댓글