publicclassSolution { public IList<int> PancakeSort(int[] arr) { IList<int> ret = new List<int>(); for (int n = arr.Length; n > 1; n--) { int index = 0; for (int i = 1; i < n; i++) { if (arr[i] >= arr[index]) { index = i; } } if (index == n - 1) { continue; } Reverse(arr, index); Reverse(arr, n - 1); ret.Add(index + 1); ret.Add(n); } return ret; }
publicvoidReverse(int[] arr, int end) { for (int i = 0, j = end; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } }
voidreverse(int *arr, int arrSize) { for (int left = 0, right = arrSize - 1; left < right; left++, right--) { int tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; } }
int *pancakeSort(int *arr, int arrSize, int *returnSize){ int *ret = (int *)malloc(sizeof(int) * (arrSize - 1) * 2); int retSize = 0; for (int n = arrSize; n > 1; n--) { int index = 0; for (int i = 1; i < n; i++) { if (arr[i] >= arr[index]) { index = i; } } if (index == n - 1) { continue; } reverse(arr, index + 1); reverse(arr, n); ret[retSize++] = index + 1; ret[retSize++] = n; } *returnSize = retSize; return ret; }
var pancakeSort = function(arr) { const ret = []; for (let n = arr.length; n > 1; n--) { let index = 0; for (let i = 1; i < n; i++) { if (arr[i] >= arr[index]) { index = i; } } if (index === n - 1) { continue; } reverse(arr, index); reverse(arr, n - 1); ret.push(index + 1); ret.push(n); } return ret; }
constreverse = (arr, end) => { for (let i = 0, j = end; i < j; i++, j--) { let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defpancakeSort(self, arr: List[int]) -> List[int]: ans = [] for n inrange(len(arr), 1, -1): index = 0 for i inrange(n): if arr[i] > arr[index]: index = i if index == n - 1: continue m = index for i inrange((m + 1) // 2): arr[i], arr[m - i] = arr[m - i], arr[i] # 原地反转 for i inrange(n // 2): arr[i], arr[n - 1 - i] = arr[n - 1 - i], arr[i] # 原地反转 ans.append(index + 1) ans.append(n) return ans
funcpancakeSort(arr []int) (ans []int) { for n := len(arr); n > 1; n-- { index := 0 for i, v := range arr[:n] { if v > arr[index] { index = i } } if index == n-1 { continue } for i, m := 0, index; i < (m+1)/2; i++ { arr[i], arr[m-i] = arr[m-i], arr[i] } for i := 0; i < n/2; i++ { arr[i], arr[n-1-i] = arr[n-1-i], arr[i] } ans = append(ans, index+1, n) } return }
复杂度分析
时间复杂度:O(n^2),其中 n 是数组 arr 的大小。总共执行至多 n - 1 次查找最大值,至多 2 \times (n - 1) 次反转数组,而查找最大值的时间复杂度是 O(n),反转数组的时间复杂度是 O(n),因此总时间复杂度是 O(n^2)。