969. Pancake Sorting
https://leetcode.com/problems/pancake-sorting/description/
由1~N组成的数组,每次能选前K个元素做翻转,要求给出任意一系列翻转方案能使得数组从小到大排好序。因为只要任意一种,而不是最短的方案,所以每次找出最大元素把它翻到最前,再把所有未排序的整个做翻转,最大元素就翻到当前范围最后去了,以此类推。
参考了这。
/*
* @lc app=leetcode id=969 lang=cpp
*
* [969] Pancake Sorting
*/
// @lc code=start
class Solution {
public:
vector<int> pancakeSort(vector<int>& A) {
vector<int> res;
for (int x = A.size(); x > 0; --x) {
int k = 0;
for (; A[k] != x; ++k) continue;
reverse(A.begin(), A.begin() + k + 1);
res.push_back(k + 1);
reverse(A.begin(), A.begin() + x);
res.push_back(x);
}
return res;
}
};
// @lc code=end
Last updated
Was this helpful?