https://leetcode.com/problems/pancake-sorting/
周赛week118题目,是个水题。
要求:将给定的数组进行排序,要求是每次只能reverse 数组前缀部分[0, …, i],例子如下:
Input: [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: A = [3, 2, 4, 1]
After 1st flip (k=4): A = [1, 4, 2, 3]
After 2nd flip (k=2): A = [4, 1, 2, 3]
After 3rd flip (k=4): A = [3, 2, 1, 4]
After 4th flip (k=3): A = [1, 2, 3, 4], which is sorted.
分析:数组 [1,2,3,4,5,6,7],如何将4放到最后一位?
k = 4,[4,3,2,1,5,6,7]
k = 7, [7,6,5,1,2,3,4]
所以,可以从大到小的顺序来排序。先排最后一位。
class Solution{
public List<Integer> pancakeSort(int[] A) {
int x = A.length - 1;
List<Integer> res = new ArrayList<>();
for(int i = x; i >= 0; i--){
int pos;
for (pos = 0; pos <= i; pos++){
if (A[pos] == i + 1) break;
}
rev(A, pos);
rev(A, i);
res.add(pos + 1);
res.add(i + 1);
}
return res;
}
private void rev(int[] A, int k){
for (int i = 0; i <= k/2; i++) {
int tmp = A[i];
A[i] = A[k - i];
A[k-i] = tmp;
}
}
}