蓝桥杯模拟双向队列

题目

 小Hi正在研究一种特殊的栈。这种栈的元素既可以从栈顶出栈,也可以从栈底出栈。(进栈还是只能从栈顶进栈)
  已知入栈的序列是1~N的一个排列,请你判断出栈序列能否是1, 2, 3, … N?
输入格式
  输入包含多组数据。
  输入第一行包含一个整数T,代表测试数据的组数。
  以下每组数据占据2行。
  第一行包含一个整数N。
  第二行包含N个整数,整数中由空格隔开。表示入栈序列。
输出格式
  对于每组数据输出YES或者NO,代表出栈序列能否是1, 2, 3, … N。
样例输入
2
5
2 4 1 3 5
5
4 3 1 5 2
样例输出
YES
NO


代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

2.读入数据

代码如下(示例):

package com.hzc.bluecap.模拟2020;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Scanner;

public class 双向队列 {
	public static void main(String[] args) {
	
		//读入数据
			Scanner sc=new Scanner(System.in);
			int n=sc.nextInt();
			ArrayList<int[]> arr=new ArrayList<>();
			for (int i = 0; i < n; i++) {
				int m=sc.nextInt();
				int[] in=new int[m];
				for (int j = 0; j < m; j++) {
					in[j]=sc.nextInt();
				}
				arr.add(in);
			}
			f(arr);
	}

	private static void f(ArrayList<int[]> arr) {
		for (int i = 0; i < arr.size(); i++) {
			int[] js = arr.get(i);
			//要查找的值
			int index=1;
			//创建双向队列
			Deque<Integer> dq=new ArrayDeque<>();
			for (int j = 0; j < js.length; j++) {
				//将数组中的数据添加到队列里面
				dq.add(js[j]);
					while(!dq.isEmpty()) {
			//在头部查找,如果等于要查找的值则出队,并查找下一个值
					if(dq.peekFirst()==index) {
							dq.removeFirst();
							index++;
		//在尾部查找,如果等于要查找的值则出队,并查找下一个值
					}else if(dq.peekLast()==index) {
							dq.removeLast();
							index++;
							//都没有直接跳出
					}else {
						break;
					}
				}	
			}
			//最后判断是否双向队列为空就行
			if(dq.isEmpty()) {
				System.out.println("YES");
			}else {
				System.out.println("NO");
			}
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值