mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-04 19:28:07 +08:00
Update 烧饼排序.md
新增了Java解决方法
This commit is contained in:
@ -150,3 +150,73 @@ void reverse(int[] arr, int i, int j) {
|
||||
</p>
|
||||
|
||||
======其他语言代码======
|
||||
|
||||
[L-WEIWEI](https://github.com/L-WWEEII) 提供 第969题的 Java 代码:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public List<Integer> pancakeSort(int[] A) {
|
||||
List<Integer> ans = new ArrayList<Integer>();
|
||||
int len = A.length;
|
||||
if(len == 0){
|
||||
return ans;
|
||||
}
|
||||
// maxIndex[0] == 当前轮次的最大元素, maxIndex[1] == 最大元素下标
|
||||
int[] maxIndex = new int[2];
|
||||
maxIndex[0] = Integer.MIN_VALUE;
|
||||
int maxCount = 0;
|
||||
// maxCount == len 时,说明完成了整个数组的最大值沉底操作,
|
||||
while(maxCount < len - 1){
|
||||
maxCount = maxValueDown(A, maxIndex, maxCount, ans);
|
||||
// 每做完一次最大值沉底操作,初始化最大元素值
|
||||
maxIndex[0] = Integer.MIN_VALUE;
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
public int maxValueDown(int[] A, int[] maxIndex, int maxCount, List<Integer> ans){
|
||||
// 遍历条件为 i < A.length - maxCount , 每次最大值沉底时,maxCount + 1,因此下次遍历即可不对最后 maxCount 个元素做操作
|
||||
for(int i = 0; i < A.length - maxCount; i++){
|
||||
// 元素大于当前储存的元素时,将值与下标 copy 到 maxIndex 数组中
|
||||
if(A[i] > maxIndex[0]){
|
||||
maxIndex[0] = A[i];
|
||||
maxIndex[1] = i;
|
||||
}
|
||||
}
|
||||
// 如果当前轮次最大元素的下标的下一位是上一轮次的最大下标,则不做翻转操作,直接返回 maxCount + 1
|
||||
if(maxIndex[1] + 1 == A.length - maxCount){
|
||||
return maxCount + 1;
|
||||
}
|
||||
// 使用最大值沉底时,当本轮最大值在首位时,不需要再将其先翻转至首位,所以不添加
|
||||
if(maxIndex[1] > 0){
|
||||
// 将该轮次要翻转的下标添加到结果集中,结果集中需要的是翻转的位置而不是下标,所以添加时下标得 + 1
|
||||
ans.add(maxIndex[1] + 1);
|
||||
}
|
||||
// 双指针原地交换数组中的值
|
||||
// 左指针指0
|
||||
int left = 0;
|
||||
// 右指针指向当前轮次最大元素的下标
|
||||
int right = maxIndex[1];
|
||||
while(left < right){
|
||||
// 交换元素值
|
||||
A[left] += A[right];
|
||||
A[right] = A[left] - A[right];
|
||||
A[left] -= A[right];
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
// 上面交换玩元素值后,当前轮次最大元素排在首位,再从上一轮次最大元素 - 1 的位置翻转
|
||||
// 则当前轮次的最大元素成功沉底
|
||||
ans.add(A.length - maxCount);
|
||||
left = 0;
|
||||
right = A.length - 1 - maxCount;
|
||||
while(left < right){
|
||||
A[left] += A[right];
|
||||
A[right] = A[left] - A[right];
|
||||
A[left] -= A[right];
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
return maxCount + 1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user