From dd5749bb3bd66898ca6a06aec00da281e9dfd87f Mon Sep 17 00:00:00 2001 From: "shuhaofeng2@creditease.cn" Date: Thu, 12 Nov 2020 01:23:59 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E3=80=90969.=20=E7=85=8E=E9=A5=BC?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E3=80=91=E3=80=90Python3=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...47\351\245\274\346\216\222\345\272\217.md" | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" index 513cbdc..67604ae 100644 --- "a/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" +++ "b/\347\256\227\346\263\225\346\200\235\347\273\264\347\263\273\345\210\227/\347\203\247\351\245\274\346\216\222\345\272\217.md" @@ -149,4 +149,41 @@ void reverse(int[] arr, int i, int j) {

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +[fengshuu](https://github.com/fengshuu) 提供 Python3 解法代码: +```python +class Solution: + # 记录反转操作序列 + def __init__(self): + self.res = [] + + def pancakeSort(self, arr: List[int]) -> List[int]: + + self.sort(arr, len(arr)) + return self.res + + def sort(self, cakes: List[int], n: int): + # base case + if 1 == n: + return + + # 寻找最大饼的索引 + max_cake_index = cakes[:n].index(n) + + # 下面进行把最大的饼放到最后的两次翻转 + # 如果最后一个饼就是最大的, 就不需要翻转, 直接进行下次递归 + if max_cake_index != n - 1: + # 第一次翻转, 将最大饼翻到最上面 + # 如果第一个饼本来就是最大的, 就不需要第一次翻转. + if max_cake_index != 0: + cakes[:max_cake_index + 1] = cakes[:max_cake_index + 1][::-1] + self.res.append(max_cake_index + 1) + + # 第二次翻转,将最大饼翻到最下面 + cakes[:n] = cakes[:n][::-1] + self.res.append(n) + + # 递归调用 + self.sort(cakes, n - 1) +``` \ No newline at end of file -- GitLab