約 2 分鐘254 字211 個單字
題目
原題頁面:https://leetcode.com/problems/partition-list/
題目型別:Linked List, Two Pointers
難度評價:Medium
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
分析
我的做法是把排在第一個大於等於x的節點後面的小於x的節點逐個摘下來,插到開頭那段小於x的節點後面。先在頭前面接一個啞節點new_head,這樣第一個節點本身就大於等於x時(比如4->1,x=3,輸出1->4),不用單獨處理頭指標。
先跳過開頭連續小於x的節點,它們本來就在正確位置,l_pos停在這段的最後一個節點上。再往後掃,parent始終是cur的前一個節點。
往後掃到小於x的節點,就摘下來接在l_pos後面,然後l_pos挪到剛接上的這個節點,下一個小於x的節點就接在它後面;大於等於x的節點原地不動,所以兩部分各自的順序都沒變。每個節點只經過常數次,時間是O(n);只改next指標、除了啞節點沒新建過節點,所以額外空間是O(1)。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution: def partition(self, head, x): if None == head or None == head.next: return head new_head = ListNode(-1) new_head.next = head tail = head while None != tail.next: tail = tail.next cur = head parent = new_head l_pos = new_head
while tail != parent and None != cur: if cur.val >= x: break parent = parent.next cur = cur.next l_pos = l_pos.next parent = parent.next if None != cur: cur = cur.next
while tail != parent and None != cur: if cur.val < x: parent.next = cur.next cur.next = l_pos.next l_pos.next = cur l_pos = l_pos.next cur = parent.next else: parent = parent.next cur = cur.next return new_head.next
|
本文地址:https://xnerv.wang/zh-tw/leetcode-partition-list/