mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 12:04:37 +08:00
feat: 【969. 煎饼排序】【Python3】
This commit is contained in:
@ -149,4 +149,41 @@ void reverse(int[] arr, int i, int j) {
|
|||||||
<img src="../pictures/qrcode.jpg" width=200 >
|
<img src="../pictures/qrcode.jpg" width=200 >
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
======其他语言代码======
|
======其他语言代码======
|
||||||
|
|
||||||
|
[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)
|
||||||
|
```
|
Reference in New Issue
Block a user