969. Pancake Sorting
找到一个排序规则即可
- 先找到最大的元素,将其反转到第一的位置。
- 再将第一的位置反转到最后一个位置
- 依次类推
每次都是经过 2*A.length
次操作
class Solution {
public int findBiggest(int[] A, int end){
int Maxx = -1;
int index = -1;
for(int i=0; i<=end; i++){
if(Maxx < A[i]){
index = i;
Maxx = A[i];
}
}
return index;
}
public void Reverse(int[] A, int end){
int left = 0;
int right = end;
int change = 0;
while(left < right){
change = A[left];
A[left] = A[right];
A[right] = change;
left++;
right--;
}
}
public List<Integer> pancakeSort(int[] A) {
LinkedList<Integer> list = new LinkedList<Integer>();
for(int i=A.length-1; i>=0; i--){
int index = findBiggest(A, i);
Reverse(A, index);
Reverse(A, i);
list.offerLast(index+1);
list.offerLast(i+1);
}
return list;
}
}