[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
return
给定一个值,把小于该值的元素按顺序放到链表前面~ 思路是用两个链表分别记录小于该值的元素和大于等于该值的元素,然后把两个链表链接起来~
时间复杂度为O(N)
还有一种解法, 设两个指针, 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
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given
1->4->3->2->5->2and 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
相关文章推荐
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode 86 Partition List
- [Leetcode] Partition List
- LeetCode() Partition List
- 【Leetcode】Partition List (Swap)
- LeetCode86 Partition List
- [LeetCode] Partition List
- [LeetCode] Partition List(!!!!巧妙的链表插入)
- leetcode -- Partition List -- 常见题型重点
- LeetCode-JAVA-Partition List
- leetcode[86]:Partition List
- Leetcode Partition List
- leetcode_question_86 Partition List
- LeetCode-Partition List
- 【leetcode】Partition List
- leetcode之Partition List
- leetcode 【 Partition List 】python 实现
- 086 Partition List [Leetcode]
- [C++]LeetCode: 19 Partition List