Skip to content

Commit 4412e5a

Browse files
committed
【update】专题-双指针
1 parent 2903f10 commit 4412e5a

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

C-算法/专题-B-双指针.md

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ Index
5858
- [I](#i)
5959
- [II](#ii)
6060
- [合并两个有序数组(Merge Sorted Array)](#合并两个有序数组merge-sorted-array)
61+
- [链表相关](#链表相关)
62+
- [链表快排](#链表快排)
63+
- [分隔链表(Partition List)](#分隔链表partition-list)
64+
- [链表快排(Sort List)](#链表快排sort-list)
6165
- [旋转链表(Rotate List)](#旋转链表rotate-list)
6266
- [其他](#其他)
6367
- [最小区间(Smallest Range)](#最小区间smallest-range)
@@ -1247,6 +1251,91 @@ class Solution:
12471251
```
12481252

12491253

1254+
# 链表相关
1255+
1256+
## 链表快排
1257+
1258+
### 分隔链表(Partition List)
1259+
> LeetCode/[86. 分隔链表](https://leetcode-cn.com/problems/partition-list/description/)
1260+
1261+
**问题描述**
1262+
```
1263+
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
1264+
1265+
你应当保留两个分区中每个节点的初始相对位置。
1266+
1267+
示例:
1268+
输入: head = 1->4->3->2->5->2, x = 3
1269+
输出: 1->2->2->4->3->5
1270+
```
1271+
1272+
**思路**
1273+
- 链表快排的中间操作
1274+
- ~~同向双指针~~——因为要求相对位置不变,所以同向双指针不够方便
1275+
- 新建两个链表,分别保存小于 x 和大于等于 x 的,最后拼接
1276+
1277+
**Python**
1278+
- 因为要求节点的相对位置不变,所以需要这么写;
1279+
- ~~如果是用在链表快排中,可以把头节点作为 x,最后把 x 插进 lo 和 hi 链表的中间;~~
1280+
- 这种写法**不适合**用在链表快排中,因为这里有**拼接**操作;
1281+
- 在实际链表快排中 partition 操作只对中间一部分执行,如果需要拼接,容易出错。
1282+
```python
1283+
# Definition for singly-linked list.
1284+
# class ListNode:
1285+
# def __init__(self, x):
1286+
# self.val = x
1287+
# self.next = None
1288+
1289+
class Solution:
1290+
def partition(self, h, x):
1291+
"""
1292+
:type h: ListNode
1293+
:type x: int
1294+
:rtype: ListNode
1295+
"""
1296+
l = lo = ListNode(0)
1297+
r = hi = ListNode(0)
1298+
1299+
while h:
1300+
if h.val < x:
1301+
l.next = h # Python 中不支持 l = l.next = h 的写法,C++ 指针可以
1302+
l = l.next
1303+
else:
1304+
r.next = h # Python 中不支持 r = r.next = h 的写法,C++ 指针可以
1305+
r = r.next
1306+
1307+
h = h.next
1308+
1309+
r.next = None # 因为尾节点可能不小于 x,所以需要断开
1310+
l.next = hi.next
1311+
1312+
return lo.next
1313+
```
1314+
1315+
### 链表快排(Sort List)
1316+
> LeetCode/[148. 排序链表](https://leetcode-cn.com/problems/sort-list/description/)
1317+
1318+
**问题描述**
1319+
```
1320+
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
1321+
1322+
示例 1:
1323+
输入: 4->2->1->3
1324+
输出: 1->2->3->4
1325+
示例 2:
1326+
输入: -1->5->3->4->0
1327+
输出: -1->0->3->4->5
1328+
```
1329+
1330+
**思路**
1331+
- 与数组快排几乎一致,只是 partition 操作需要从左向右遍历
1332+
1333+
**C++**
1334+
```C++
1335+
1336+
```
1337+
1338+
12501339
## 旋转链表(Rotate List)
12511340
> LeetCode/[61. 旋转链表](https://leetcode-cn.com/problems/rotate-list/description/)
12521341
@@ -1323,6 +1412,7 @@ class Solution:
13231412
```
13241413

13251414
**代码 2**
1415+
- 代码量少一点,但是遍历的长度要多一点。
13261416
```python
13271417
class Solution:
13281418
def rotateRight(self, h, k):

0 commit comments

Comments
 (0)