友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
86. 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:
Input: head = 1->4->3->2->5->2, x = 3 Output: 1->2->2->4->3->5
思路分析
思路很简单,直接双指针维护大小两个队列就好。
-
一刷
-
二刷
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
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
* Memory Usage: 37.5 MB, less than 5.77% of Java online submissions for Partition List.
*
* @author D瓜哥 · https://www.diguage.com
* @since 2020-02-05 19:14
*/
public ListNode partition(ListNode head, int x) {
if (Objects.isNull(head)) {
return null;
}
ListNode dummySmall = new ListNode(0);
ListNode dummyLarge = new ListNode(0);
ListNode tailSmall = dummySmall;
ListNode tailLarge = dummyLarge;
while (Objects.nonNull(head)) {
if (head.val < x) {
tailSmall.next = head;
tailSmall = tailSmall.next;
} else {
tailLarge.next = head;
tailLarge = tailLarge.next;
}
head = head.next;
}
tailLarge.next = null;
tailSmall.next = dummyLarge.next;
return dummySmall.next;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-09-14 16:17:29
*/
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode();
ListNode smallTail = small;
ListNode big = new ListNode();
ListNode bigTail = big;
while (head != null) {
if (head.val < x) {
smallTail.next = head;
smallTail = smallTail.next;
} else {
bigTail.next = head;
bigTail = bigTail.next;
}
head = head.next;
}
smallTail.next = big.next;
bigTail.next = null;
return small.next;
}