未验证 提交 3effc383 编写于 作者: B BruceCat 提交者: GitHub

【969. 煎饼排序】【Java】

【969. 煎饼排序】【Java】
......@@ -149,4 +149,74 @@ void reverse(int[] arr, int i, int j) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ No newline at end of file
======其他语言代码======
[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;
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册