From 18288033cf1de53e1b10dc61d50f678d6d301328 Mon Sep 17 00:00:00 2001 From: KAGAWA317 <53385235+KAGAWA317@users.noreply.github.com> Date: Wed, 24 Jun 2020 12:39:21 +0800 Subject: [PATCH] =?UTF-8?q?k=E4=B8=AA=E4=B8=80=E7=BB=84=E5=8F=8D=E8=BD=AC?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20(#350)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Kristifler --- ...15\350\275\254\351\223\276\350\241\250.md" | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" index a338879..a637312 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/k\344\270\252\344\270\200\347\273\204\345\217\215\350\275\254\351\223\276\350\241\250.md" @@ -175,8 +175,51 @@ private: ![labuladong](../pictures/labuladong.jpg) + +[KAGAWA317](https://github.com/KAGAWA317) 提供Python3解法代码: + +```python +# 反转区间 [a, b) 的元素 +def reverse(a, b): + pre = None + cur = a + while cur != b: + cur.next, pre, cur = pre, cur, cur.next + return pre +``` + +[KAGAWA317](https://github.com/KAGAWA317) 提供Python3解法代码: + +```python +class Solution: + def reverseKGroup(self, head: ListNode, k: int) -> ListNode: + if not head: + return + # 区间 [a, b) 包含 k 个待反转元素 + a = b = head + for _ in range(k): + # 不足 k 个,不需要反转,base case + if not b: + return head + b = b.next + + # 反转区间 [a, b) 的元素 + def reverse(a, b): + pre = None + cur = a + while cur != b: + cur.next, pre, cur = pre, cur, cur.next + return pre + + # 反转前 k 个元素 + newHead = reverse(a, b) + # 递归反转后续链表并连接起来 + a.next = self.reverseKGroup(b, k) + return newHead +``` + [上一篇:如何寻找最长回文子串](../高频面试系列/最长回文子串.md) [下一篇:如何判定括号合法性](../高频面试系列/合法括号判定.md) -[目录](../README.md#目录) +[目录](../README.md#目录) \ No newline at end of file -- GitLab