题目地址:
https://www.lintcode.com/problem/pancake-sorting/description
给定一个数组 A A A,要求将其排序。只能对数组进行翻转 A [ 0 : i ] A[0:i] A[0:i]的操作,别的操作不允许做(非修改的操作是可以做的,比如扫描数组等等)。
思路是,每次扫描出未排好序的前缀中的最大值,然后将其先翻转到 A [ 0 ] A[0] A[0],接着将其翻转到它该在的位置上。例如对于数组 ( 2 , 1 , 3 , 5 , 4 ) (2,1,3,5,4) (2,1,3,5,4),最大值是 5 5 5,那就先将其翻转到 0 0 0的位置,得 ( 5 , 3 , 1 , 2 , 4 ) (5,3,1,2,4) (5,3,1,2,4),最后再将 5 5 5翻到它该在的位置上,得 ( 4 , 2 , 1 , 3 , 5 ) (4,2,1,3,5) (4,2,1,3,5)。代码如下:
public class Solution {
/**
* @param array: an integer array
* @return: nothing
*/
public void pancakeSort(int[] array) {
// Write your code here
// idx存当前未排好序的前缀的最后一个数字的下标
int idx = array.length - 1;
while (idx > 0) {
// 找到最大值所在的下标
int maxIdx = 0, max = Integer.MIN_VALUE;
for (int i = 0; i <= idx; i++) {
if (array[i] > max) {
max = array[i];
maxIdx = i;
}
}
// 如果最大值不在idx的位置,则翻转两次
if (maxIdx != idx) {
flip(array, maxIdx);
flip(array, idx);
}
// 每次将最大值排到后面后,就缩小排序范围
idx--;
}
}
private void flip(int[] array, int i) {
for (int j = 0; j < i; j++, i--) {
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
}
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间 O ( 1 ) O(1) O(1)。