# 5.7阿里笔试第二题

Java这样可以么，大神们看看

```import java.util.HashMap;
import java.util.Queue;
import java.util.Scanner;

public class aliCoding2 {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[] preorder = new int[n];
int[] ret = new int[n];
int i = 0;
while (i < n) {
preorder[i] = in.nextInt();
i++;
}
in.close();
if (n < 2 || m == 0) {
ret = preorder;
} else {
Queue<Integer> queue = new LinkedList<Integer>();
HashMap<Integer, Integer> endMap = new HashMap<>();
queue.offer(0);
endMap.put(0, n - 1);
ret[0] = preorder[0];
while (queue.size() > 0) {
int count = queue.size();
for (int j = 0; j < count; j++) {
int currentIndex = queue.poll();
int currentValue = preorder[currentIndex];
int currentEnd = endMap.getOrDefault(currentIndex, n - 1);
int nextIndex = currentIndex + 1;
int left = 0;
int right = 0;
if (nextIndex <= currentEnd && preorder[nextIndex] < currentValue) {
// 有左叶子
left = nextIndex;
endMap.put(left, nextIndex);
nextIndex++;
}
while (nextIndex <= currentEnd) {
int nextValue = preorder[nextIndex];
if (nextValue > currentValue) {
right = nextIndex;
endMap.put(right, currentEnd);
break;
}
if (left != 0 && endMap.containsKey(left))
endMap.put(left, nextIndex);
nextIndex++;
}
}
// 位移数
Integer[] a = queue.toArray(new Integer[queue.size()]);
System.out.println(queue);
for (int j = 0; j < a.length; j++) {
int oldIndex = a[j];
int newIndex = a[(j + m) % a.length];
System.out.println(oldIndex + " to " + newIndex);
ret[newIndex] = preorder[oldIndex];
}
}
}
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
sb.append(String.valueOf(ret[j]));
sb.append(" ");
}
System.out.println(sb.toString());
}
}
```

# 相关热帖

• 回复(0) 发表于 2021-05-22 17:02:32
• 回复(1) 发表于 2021-05-14 19:05:42
• 回复(2) 发表于 2021-05-08 14:11:13
• 回复(1) 发表于 2021-05-04 19:26:54
• 回复(0) 发表于 2021-04-18 17:54:18

# 技术交流近期热帖

• 回复(0) 发表于 2021-06-16 16:50:02
• 回复(0) 发表于 2021-06-16 16:41:55
• 回复(0) 发表于 2021-06-16 16:12:37
• 回复(0) 发表于 2021-06-16 14:06:40
• 回复(1) 发表于 2021-06-16 20:41:13
• 回复(0) 发表于 2021-06-16 15:27:46

# 近期精华帖

• 回复(13) 发表于 2021-05-17 08:28:50
• 回复(1) 发表于 2021-05-31 14:23:14
• 回复(2) 发表于 2021-06-04 15:11:09
• 回复(6) 发表于 2021-06-15 19:01:14
• 回复(3) 发表于 2021-05-29 14:31:50

# 热门推荐

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题