您的位置:首页 > 其它

[Leetcode]Partition List

2014-12-25 14:30 393 查看
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
.

给定一个值,把小于该值的元素按顺序放到链表前面~   思路是用两个链表分别记录小于该值的元素和大于等于该值的元素,然后把两个链表链接起来~

时间复杂度为O(N)

class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
if head is None: return None
largerHead = larger = ListNode(0)
smallerHead = smaller = ListNode(0)
cur = head
while cur:
if cur.val < x:
smaller.next = cur; smaller = smaller.next
else:
larger.next = cur; larger = larger.next
cur = cur.next
larger.next, smaller.next = None, largerHead.next
return smallerHead.next


还有一种解法, 设两个指针, walker指针指向当前小于x的最后一个节点,runner指针往前扫描~  如果runner.next.val >= x,runner指针继续往前扫描,否则,把小于x的元素移到前面,并更新walker指针~ 时间复杂度为O(N), 空间复杂度为O(1)

class Solution:
# @param head, a ListNode
# @param x, an integer
# @return a ListNode
def partition(self, head, x):
if head is None: return None
dummy = ListNode(0)
dummy.next = head
walker, runner = dummy, dummy
while runner.next:
if runner.next.val < x:
if walker != runner:
next = runner.next.next
runner.next.next = walker.next
walker.next = runner.next
runner.next = next
else:
runner = runner.next
walker = walker.next
else:
runner = runner.next
return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: