Skip to content

Commit ed8e311

Browse files
akijoeylabuladong
authored andcommitted
Update 烧饼排序.md
1 parent 53d4895 commit ed8e311

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

算法思维系列/烧饼排序.md

+36
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,42 @@ void reverse(int[] arr, int i, int j) {
123123

124124
![labuladong](../pictures/labuladong.jpg)
125125

126+
[AkiJoey](https://github.com/AkiJoey) 提供 C++ 解法代码:
127+
```c++
128+
class Solution {
129+
public:
130+
vector<int> pancakeSort(vector<int>& A) {
131+
sort(A, A.size());
132+
return res;
133+
}
134+
private:
135+
vector<int> res;
136+
void sort(vector<int>& arr, int n) {
137+
// base case
138+
if (n == 1)
139+
return;
140+
141+
// 寻找最大饼的索引
142+
int max = 0, index = 0;
143+
for(int i = 0;i < n;i++)
144+
if (arr[i] > max) {
145+
max = arr[i];
146+
index = i;
147+
}
148+
149+
// 第一次翻转,将最大饼翻到最上面
150+
reverse(arr.begin(), arr.begin() + index + 1);
151+
res.emplace_back(index + 1);
152+
153+
// 第二次翻转,将最大饼翻到最下面
154+
reverse(arr.begin(), arr.begin() + n);
155+
res.emplace_back(n);
156+
157+
// 递归调用
158+
sort(arr, n - 1);
159+
}
160+
};
161+
```
126162
127163
[上一篇:拆解复杂问题:实现计算器](../数据结构系列/实现计算器.md)
128164

0 commit comments

Comments
 (0)