Skip to content

Commit c4c5ea8

Browse files
committed
重构“字符串”这章
1 parent a19ff0f commit c4c5ea8

File tree

3 files changed

+183
-95
lines changed

3 files changed

+183
-95
lines changed

C++/LeetCodet题解(C++版).pdf

3.96 KB
Binary file not shown.

C++/chapLinearList.tex

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2271,7 +2271,38 @@ \subsubsection{分析}
22712271
\subsubsection{代码}
22722272
\begin{Code}
22732273
// LeetCode, Reverse Nodes in k-Group
2274-
// 时间复杂度O(n),空间复杂度O(1)
2274+
// 递归版,时间复杂度O(n),空间复杂度O(1)
2275+
class Solution {
2276+
public:
2277+
ListNode *reverseKGroup(ListNode *head, int k) {
2278+
if (head == nullptr || head->next == nullptr || k < 2)
2279+
return head;
2280+
2281+
ListNode *next_group = head;
2282+
for (int i = 0; i < k; ++i) {
2283+
if (next_group)
2284+
next_group = next_group->next;
2285+
else
2286+
return head;
2287+
}
2288+
// next_group is the head of next group
2289+
// new_next_group is the new head of next group after reversion
2290+
ListNode *new_next_group = reverseKGroup(next_group, k);
2291+
ListNode *prev = NULL, *cur = head;
2292+
while (cur != next_group) {
2293+
ListNode *next = cur->next;
2294+
cur->next = prev ? prev : new_next_group;
2295+
prev = cur;
2296+
cur = next;
2297+
}
2298+
return prev; // prev will be the new head of this group
2299+
}
2300+
};
2301+
\end{Code}
2302+
2303+
\begin{Code}
2304+
// LeetCode, Reverse Nodes in k-Group
2305+
// 迭代版,时间复杂度O(n),空间复杂度O(1)
22752306
class Solution {
22762307
public:
22772308
ListNode *reverseKGroup(ListNode *head, int k) {
@@ -2330,7 +2361,7 @@ \subsubsection{分析}
23302361
\subsubsection{代码}
23312362
\begin{Code}
23322363
// LeetCode, Copy List with Random Pointer
2333-
// 两遍扫描
2364+
// 两遍扫描,时间复杂度O(n),空间复杂度O(1)
23342365
class Solution {
23352366
public:
23362367
RandomListNode *copyRandomList(RandomListNode *head) {

0 commit comments

Comments
 (0)