提交 ed8e311c 编写于 作者: A AkiJoey 提交者: labuladong

Update 烧饼排序.md

上级 53d48955
......@@ -123,6 +123,42 @@ void reverse(int[] arr, int i, int j) {
![labuladong](../pictures/labuladong.jpg)
[AkiJoey](https://github.com/AkiJoey) 提供 C++ 解法代码:
```c++
class Solution {
public:
vector<int> pancakeSort(vector<int>& A) {
sort(A, A.size());
return res;
}
private:
vector<int> res;
void sort(vector<int>& arr, int n) {
// base case
if (n == 1)
return;
// 寻找最大饼的索引
int max = 0, index = 0;
for(int i = 0;i < n;i++)
if (arr[i] > max) {
max = arr[i];
index = i;
}
// 第一次翻转,将最大饼翻到最上面
reverse(arr.begin(), arr.begin() + index + 1);
res.emplace_back(index + 1);
// 第二次翻转,将最大饼翻到最下面
reverse(arr.begin(), arr.begin() + n);
res.emplace_back(n);
// 递归调用
sort(arr, n - 1);
}
};
```
[上一篇:拆解复杂问题:实现计算器](../数据结构系列/实现计算器.md)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册