我是靠谱客的博主 威武火龙果,这篇文章主要介绍【LeetCode每天一题】Partition List(分区链表),现在分享给大家,希望可以做个参考。

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.

Example:

复制代码
1
2
  Input: head = 1->4->3->2->5->2, x = 3   Output: 1->2->2->4->3->5

思路

复制代码
1
  这道题最简单的思路就是我们可以将链表中的数据全部都添加进数组中,然后对数组中的元素按照x进行划分,得到划分之后的数组再组成链表。但是这种办法再应对链表比较长的时候就会存在问题。时间复杂度为O(n)(省略了系数), 空间复杂度为O(n)。另一种解法是我们可以直接该改变指针的方向,原地对链表进行分区。时间复杂度为O(n), 空间复杂度为O(1)。
图示解法

复制代码
1
解决代码

复制代码
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
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def partition(self, head, x): 9 """ 10 :type head: ListNode 11 :type x: int 12 :rtype: ListNode 13 """ 14 if not head or not head.next: 15 return head 16 17 res = ListNode(0) = one # 哨兵节点 18 19 while True: 20 while one.next and one.next.val < x: # 便利到下一个节点大于x市停止。 21 one = one.next 22 two = one.next # two节点从这个one的下一个节点来找到下一个节点小于x的系欸但使停止 23 while two.next and two.next.val >= x: 24 two = two.next 25 26 if not two.next or not one.next: # 如果两个节点任意一个为空,则表示没找到满足条件的节点。 27 return res.next 28 tem = two.next # 交换节点的指向为止,注意顺序不能改变,否则会出错。 29 two.next = tem.next 30 tem.next = one.next 31 one.next = tem
复制代码
1

转载于:https://www.cnblogs.com/GoodRnne/p/10808914.html

最后

以上就是威武火龙果最近收集整理的关于【LeetCode每天一题】Partition List(分区链表)的全部内容,更多相关【LeetCode每天一题】Partition内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(70)

评论列表共有 0 条评论

立即
投稿
返回
顶部