50-左移右移(蓝桥杯)

问题描述

小蓝有一个长度为 N 的数组, 初始时从左到右依次是 1,2,3,…N

之后小蓝对这个数组进行了 M 次操作, 每次操作可能是以下 2 种之一:

  1. 左移 x, 即把 x 移动到最左边。

  1. 右移 x, 即把 x 移动到最右边。

请你回答经过 M 次操作之后, 数组从左到右每个数是多少?

输入格式

第一行包含 2 个整数, NM

以下 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;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月亮被咬碎成星星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值