Given an array of integers arr
, sort the array by performing a series of pancake flips.
In one pancake flip we do the following steps:
- Choose an integer
k
where1 <= k <= arr.length
. - Reverse the sub-array
arr[1...k]
.
For example, if arr = [3,2,1,4]
and we performed a pancake flip choosing k = 3
, we reverse the sub-array [3,2,1]
, so arr = [1,2,3,4]
after the pancake flip at k = 3
.
Return the k
-values corresponding to a sequence of pancake flips that sort arr
. Any valid answer that sorts the array within 10 * arr.length
flips will be judged as correct.
Example 1:
Input: arr = [3,2,4,1]
Output: [4,2,4,3]
Explanation:
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = [3, 2, 4, 1]
After 1st flip (k = 4): arr = [1, 4, 2, 3]
After 2nd flip (k = 2): arr = [4, 1, 2, 3]
After 3rd flip (k = 4): arr = [3, 2, 1, 4]
After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.
Notice that we return an array of the chosen k values of the pancake flips.
Example 2:
Input: arr = [1,2,3]
Output: []
Explanation: The input is already sorted, so there is no need to flip anything.
Note that other answers, such as [3, 3], would also be accepted.
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= arr.length
- All integers in
arr
are unique (i.e.arr
is a permutation of the integers from1
toarr.length
).
這道題給了長度為n的數組,由1到n的組成,順序是打亂的。現在說我們可以任意翻轉前k個數字,k的范圍是1到n,問怎么個翻轉法能將數組翻成有序的。題目說並不限定具體的翻法,只要在 10*n
的次數內翻成有序的都是可以的,任你隨意翻,就算有無效的步驟也無所謂。題目中給的例子1其實挺迷惑的,因為並不知道為啥要那樣翻,也沒有一個固定的翻法,所以可能會誤導大家。必須要自己想出一個固定的翻法,這樣才能應對所有的情況。博主想出的方法是每次先將數組中最大數字找出來,然后將最大數字翻轉到首位置,然后翻轉整個數組,這樣最大數字就跑到最后去了。然后將最后面的最大數字去掉,這樣又重現一樣的情況,重復同樣的步驟,直到數組只剩一個數字1為止,在過程中就把每次要翻轉的位置都記錄到結果 res 中就可以了,注意這里 C++ 的翻轉函數 reverse 的結束位置是開區間,很容易出錯,參見代碼如下:
解法一:
class Solution {
public:
vector<int> pancakeSort(vector<int>& arr) {
vector<int> res;
while (arr.size() > 1) {
int n = arr.size(), i = 0;
for (; i < n; ++i) {
if (arr[i] == n) break;
}
res.push_back(i + 1);
reverse(arr.begin(), arr.begin() + i + 1);
res.push_back(n);
reverse(arr.begin(), arr.end());
arr.pop_back();
}
return res;
}
};
上論壇看了一下,發現高分解法都是用類似的思路,看來英雄所見略同啊,哈哈~ 不過博主上面的方法可以略微優化一下,並不用真的從數組中移除數字,只要確定個范圍就行了,右邊界不斷的縮小,效果跟移除數字一樣的,參見代碼如下:
解法二:
class Solution {
public:
vector<int> pancakeSort(vector<int>& arr) {
vector<int> res;
for (int i = arr.size(), j; i > 0; --i) {
for (j = 0; arr[j] != i; ++j);
reverse(arr.begin(), arr.begin() + j + 1);
res.push_back(j + 1);
reverse(arr.begin(), arr.begin() + i);
res.push_back(i);
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/969
參考資料:
https://leetcode.com/problems/pancake-sorting/
https://leetcode.com/problems/pancake-sorting/discuss/214213/JavaC%2B%2BPython-Straight-Forward