问题描述
小蓝有一个长度为 N 的数组, 初始时从左到右依次是 1,2,3,…N 。
之后小蓝对这个数组进行了 M 次操作, 每次操作可能是以下 2 种之一:
左移 x, 即把 x 移动到最左边。
右移 x, 即把 x 移动到最右边。
请你回答经过 M 次操作之后, 数组从左到右每个数是多少?
输入格式
第一行包含 2 个整数, N 和 M 。
以下 M 行每行一个操作, 其中 “L x "表示左移 ,R x "表示右移 x 。
输出格式
输出 N 个数, 代表操作后的数组。
样例输入
5 3
L 3
L 2
R 1
样例输出
2 3 4 5 1
样例说明
样例中的数组变化如下:
[1,2,3,4,5]→[3,1,2,4,5]→[2,3,1,4,5]→[2,3,4,5,1][1,2,3,4,5]→[3,1,2,4,5]→[2,3,1,4,5]→[2,3,4,5,1]
评测用例规模与约定
运行限制
最大运行时间:3s
最大运行内存: 512M
源码:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class 左移右移 {
static class Node{
int val;
Node pre;
Node next;
public Node(int val,Node pre,Node next) {
this.val=val;
this.pre=pre;
this.next=next;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
int m=scanner.nextInt();
Node head=new Node(-1, null, null);
Node last=new Node(-1, null, null);
Map<Integer, Node> map=new HashMap<Integer,Node>();
Node pre=head;
for (int i = 1; i <=n; i++) {
pre.next=new Node(i, pre, null);
pre=pre.next;
map.put(i, pre);
}
pre.next=last;
last.pre=pre;
for (int i = 0; i < m; i++) {
char c=scanner.next().charAt(0);
int k=scanner.nextInt();
//删除节点
Node node=map.get(k);
node.pre.next=node.next;
node.next.pre=node.pre;
if (c=='L') {
node.next=head.next;
head.next.pre=node;
head.next=node;
node.pre=head;
}else {
node.pre=last.pre;
last.pre.next=node;
node.next=last;
last.pre=node;
}
}
pre=head.next;
while(pre!=last) {
System.out.print(pre.val+" ");
pre=pre.next;
}
}
}