提交 9519492a 编写于 作者: S shuhaofeng2@creditease.cn

feat: 【969. 煎饼排序】【C++】

上级 36f59b6f
......@@ -149,4 +149,47 @@ void reverse(int[] arr, int i, int j) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
[fengshuu](https://github.com/fengshuu) 提供 C++ 解法代码:
```cpp
class Solution {
public:
vector<int> pancakeSort(vector<int>& arr) {
sort(arr, arr.size());
return res;
}
private:
// 记录反转操作序列
vector<int> res;
void sort(vector<int>& cakes, int n){
// base case
if(n == 1) return;
// 寻找最大饼的索引
int maxCakeIndex = max_element(cakes.begin(), cakes.begin() + n) - cakes.begin();
// 下面进行把最大的饼放到最后的两次翻转
// 如果最后一个饼就是最大的, 就不需要翻转, 直接进行下次递归
if (maxCakeIndex == n-1){
sort(cakes, n - 1);
return;
}
// 第一次翻转, 将最大饼翻到最上面
// 如果第一个饼本来就是最大的, 就不需要第一次翻转.
if (maxCakeIndex != 0) {
reverse(cakes.begin(), cakes.begin() + maxCakeIndex + 1);
res.push_back(maxCakeIndex + 1);
}
// 第二次翻转,将最大饼翻到最下面
reverse(cakes.begin(), cakes.begin() + n);
res.push_back(n);
// 递归调用
sort(cakes, n - 1);
}
};
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册