Algo-Lab 2 Stack Queue ADT

Lab 2: Stack & Queue ADT

image-20240923223516163

Part 1

​ 这里只说一下最小栈的思路,我们可以在定义一个栈,来同步存储当前情况下的占的最小值。最小栈第一时间的想法可能是设定一个变量,每次push进来栈中的元素进行对比,保持最小值,但是这样做并没有考虑到如果POP时的各种情况。因此,我们设置一个最小值的栈,他和存储的栈同步Push和Pop,只是,它每次push 的是栈目前存储的元素中的最小的值,这样就解决了 Pop 后的最小值问题了。

public class StackMin<AnyType extends Comparable<AnyType>> implements StackInterface<AnyType> {private static final int MAX_SIZE = 1024;private AnyType[] xstack;private AnyType[] minstack;private int size;public StackMin() {this.xstack = (AnyType[]) new Object[MAX_SIZE];this.minstack = (AnyType[]) new Object[MAX_SIZE];this.size = 0;}@Overridepublic int size() {return this.size;}@Overridepublic AnyType pop() throws EmptyStackException {if (isEmpty()) {throw new EmptyStackException();}return this.xstack[--this.size];}@Overridepublic AnyType peek() throws EmptyStackException {if (isEmpty()) {throw new EmptyStackException();}return this.xstack[this.size - 1];}@Overridepublic void push(AnyType item) {if (this.size < MAX_SIZE) {this.xstack[this.size++] = item;if (size == 0 || item.compareTo(this.minstack[size - 1]) < 0) {this.minstack[this.size] = item;} else {this.minstack[this.size] = this.minstack[size - 1];}}}@Overridepublic void clear() {this.size = 0;}@Overridepublic boolean isEmpty() {return size() == 0;}public AnyType findMin() {return this.minstack[this.size - 1];}
}

image-20240923223533506

Part 2

​ 这个题目的主要思想是,寻找第一个比自己小的数距离,从暴力的角度来想,我每次遍历一个数字,就从这个数向前遍历,直到遇到比自己大的数为止,这样的时间复杂度是n方;考虑优化的话,可以进一步想到,如果前面的数比自己小,那么它的结果的距离范围的数字都会比自己小,则可以剪枝一部分遍历的时间;我们可以进一步的优化,设置一个栈,如果当前元素小于栈顶元素,则索引的距离即为所求;如果当前元素比栈顶元素值大的时候,则一直Pop出站,直到栈顶元素更大的时候,这时,两者的索引距离就是范围。下面是两种情况下的代码,一种是直接给了完整的数组可以查询的,一种是等待输入流随时输入随时输出的。

/*** Simple computeSpan static function* working on arrays*/public static int[] computeSpan(int[] input) {int len = input.length;int[] spans = new int[len];Stack<Integer> stack = new Stack<>();for (int i = 0; i < len; i++) {while (!stack.isEmpty() && input[stack.peek()] <= input[i]) {stack.pop();}spans[i] = (stack.isEmpty()) ? (i + 1) : (i - stack.peek());stack.push(i);}return spans;}/*** Compute the span of the input values* using a stack.* Complexity: THETA(n) where is n is the* number of values to compute the span of*/public void computeSpan() {Stack<Integer> priceStack = new Stack<>();Stack<Integer> indexStack = new Stack<>();int day = 0;while (input.hasNextInt()) {int price = input.nextInt();int span = 1;while (!priceStack.isEmpty() && priceStack.peek() <= price) {priceStack.pop();indexStack.pop();}if (indexStack.isEmpty()) {span = day + 1;} else {span = day - indexStack.peek();}priceStack.push(price);indexStack.push(day);output.printf("value: %d span: %d\n", price, span);day++;}}

image-20240923223542933

Part 3

​ 用链表写一个队列就不说了,寻找pair,浅谈一下,暴力的话,n方的复杂度依次遍历;优化的话,放在哈希表中,减去O(n)的查询的复杂度

public static void showPairs(int n, String fileName) throws FileNotFoundException, EmptyQueueException {ListQueue<Integer> queue = new ListQueue<>();Scanner scanner = new Scanner(new File(fileName));while (scanner.hasNextInt()) {queue.offer(scanner.nextInt());}scanner.close();Map<Integer, Integer> map = new HashMap<>();int index = 0;while (!queue.isEmpty()) {Integer num = queue.poll();if (map.containsKey(num - n)) {System.out.println("(" + (num - n) + "," + num + ")");}map.put(num, index++);}}

image-20240923223552679

Part 4

​ 用栈来写一个队列,思路也很简单,使用两个栈,一个输入,一个输出,当输出栈为空时,将输入栈的值全部压到输出栈中

package tiei.aads.adt;import java.util.Stack;/*** A class for queues implemented with stacks*/
public class StackQueue<AnyType> implements QueueInterface<AnyType> {private Stack<AnyType> instack = new Stack<>();private Stack<AnyType> outstack = new Stack<>();@Overridepublic int size() {return this.instack.size() + this.outstack.size();}@Overridepublic boolean isEmpty() {return this.instack.isEmpty() && this.outstack.isEmpty();
//        return QueueInterface.super.isEmpty();}@Overridepublic void offer(AnyType item) {this.instack.push(item);}@Overridepublic AnyType poll() throws EmptyQueueException {if(this.outstack.isEmpty()){while (this.instack.isEmpty()){this.outstack.push(this.instack.pop());}}return outstack.pop();}@Overridepublic AnyType peek() throws EmptyQueueException {if(this.outstack.isEmpty()){while (this.instack.isEmpty()){this.outstack.push(this.instack.pop());}}return outstack.peek();}
}

image-20240923223607171

Part 5

​ 是一个经典的T形火车问题,主要思路就是,使用一个Map,存储下一个目标火车所在的栈,然后依次将不是目标的元素存储到另一个栈中(因为你需要考虑最简洁的移动方式,所以需要精准找到目标火车的位置;如果不需要最简洁的要求,完全可以在两个栈中依次寻找就跟我下面还没有优化完全的代码一样)(过段时间我一定改)

package tiei.aads.adt;import java.util.*;/*** A class to arrange train configuration*/
public class TrainManagement {private String[] from; // the initial orderingprivate String[] to;   // the final orderingprivate StackInterface<String> U; // to hold the cars on track U(nsorted)private StackInterface<String> T; // to hold the cars on track T(emporary)private StackInterface<String> S; // to hold the cars on track S(orted)private Map<String, StackInterface<String>> map = new HashMap<>();/*** Build a TrainManagement object* Preconditions:* 'from' and 'to' have the same size N and are* both permutations of each other*/public TrainManagement(String[] from, String[] to) {this.from = from;this.to = to;U = new ArrayStack<>();T = new ArrayStack<>();S = new ArrayStack<>();for (int i = from.length - 1; i >= 0; i--) {U.push(from[i]);map.put(from[i], U);}}/*** Output the basic move commands to transfer* the cars from the 'from' order on track U* to the 'to' order on track S*/public void arrange() throws EmptyStackException {int toIndex = 0;while (toIndex < to.length) {String targetCar = to[toIndex];boolean found = false;while (!U.isEmpty()) {String car = U.pop();System.out.println("move car " + car + " from U to T");T.push(car);if (car.equals(targetCar)) {found = true;System.out.println("move car " + car + " from T to S");T.pop();toIndex++;break;}}while (!T.isEmpty() && !found) {String car = T.pop();System.out.println("move car " + car + " from T to U");U.push(car);}}}/*** A short main for quick testing*/public static void main(String[] args) throws EmptyStackException {String[] from = {"33", "11", "44", "22"};String[] to = {"11", "22", "33", "44"};TrainManagement tm = new TrainManagement(from, to);tm.arrange();}// expected output//// move car 33 from U to T// move car 11 from U to T// move car 11 from T to S// move car 44 from U to T// move car 22 from U to T// move car 22 from T to S// move car 44 from T to U// move car 33 from T to S// move car 44 from U to T// move car 44 from T to S
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/148208.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

每日一练:二叉树的直径

543. 二叉树的直径 - 力扣&#xff08;LeetCode&#xff09; 一、题目要求 给你一棵二叉树的根节点&#xff0c;返回该树的 直径 。 二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。 两节点之间路径的 长度 由它们之…

2024.9.23 作业

统计家目录下.c文件的个数 定义一个稀疏数组(下标不连续)&#xff0c;写一个函数&#xff0c;求该稀疏数组的和&#xff0c;要求稀疏数组中的数值通过参数传递到函数中。 arr([2]9 [4]8 [30]23 [24]3 [21]7) 思维导图

高效高质量SCI论文撰写及投稿

第一章、论文写作准备即为最关键 1、科技论文写作前期的重要性及其分类 2、AI工具如何助力学术论文 3、研究主题确定及提高创新性 兴趣与背景&#xff1a;选择一个您感兴趣且有背景知识的研究领域。 创新性&#xff1a;选题和研究设计阶段如何提高学术创新性的方法。 研究缺…

【React】原理

笔记来源&#xff1a;小满zs 虚拟 DOM // react.js // jsx > babel | swc > React.createElement const React {createElement(type, props, ...children) {return {type,props: {...props,children: children.map(child > typeof child object ? child : React.cr…

3 pyqt5 Layout布局(保证主界面缩放各组件也对应缩放)== 主要有Qt Designer和完全代码设置两种设计方式(根据自己情况选择即可)

文章目录 前言一、Layout的类别二、使用Qt Designer进行Layout布局三、完全使用代码进行Layout布局前言 本节我们的http测试的例子,只实现界面方面的逻辑,底层不用管。我们主要的目的是通过这个例子设计界面布局。 我们前面写的界面程序有个问题,如果你用鼠标拖拽主窗口边…

超分之SPIN

Lightweight image super-resolution with superpixel token interaction[C]利用超像素token交互实现轻量级图像超分辨率Zhang A, Ren W, Liu Y, et al.Proceedings of the IEEE/CVF International Conference on Computer Vision. 2023: 12728-12737. 文章目录 摘要1. 引言2. …

828华为云征文 | 云服务器Flexus X实例,Docker集成搭建Mysql集群

828华为云征文 | 云服务器Flexus X实例&#xff0c;Docker集成搭建Mysql集群 MySQL 集群是一种高可用性、高性能的数据库解决方案&#xff0c;旨在支持分布式应用程序&#xff0c;允许多个 MySQL 实例以集群的方式共同工作&#xff0c;提供数据冗余和故障恢复能力 搭建Mysql集群…

C++11新特性和扩展(1)

个人主页&#xff1a;C忠实粉丝 欢迎 点赞&#x1f44d; 收藏✨ 留言✉ 加关注&#x1f493;本文由 C忠实粉丝 原创 C11新特性和扩展 收录于专栏 [C进阶学习] 本专栏旨在分享学习C的一点学习笔记&#xff0c;欢迎大家在评论区交流讨论&#x1f48c; 目录 1.C11简介 2. 列表初始…

数据转换器——佛朗哥Chater2

【注:本文基于《数据转换器》一书进行学习、总结编撰,适合新手小白进行学习】 目录 2.1 数据转换器类别 2.2 工作条件 2.3 转换器性能参数 2.3.1 基本特性参数 2.4 静态性能参数 2.5 动态性能参数 2.6 数字和开关性能参数 2.1 数据转换器类别 转换器类型可以被分为两…

JUC高并发编程1:JUC概述

1 什么是JUC 1.1 JUC简介 JUC就是 java.util .concurrent 工具包的简称。这是一个处理线程的工具包&#xff0c;JDK 1.5 开始出现的。 1.2 进程与线程 进程&#xff08;Process&#xff09;和线程&#xff08;Thread&#xff09;是操作系统中用于实现多任务处理的两种基本概…

python爬虫案例——抓取链家租房信息

文章目录 1、任务目标2、分析网页3、编写代码1、任务目标 目标站点:链家租房版块(https://bj.lianjia.com/zufang/) 要求:抓取该链接下前5页所有的租房信息,包括:标题、详情信息、详情链接、价格 如: 2、分析网页 用浏览器打开链接,按F12或右键检查,进入开发者模式;因…

spring 代码执行(CVE-2018-1273) 靶场攻略

靶场环境 vulhub/spring/CVE-2018-1273 漏洞复现 1.访问靶场地址 2.填写注册信息&#xff0c;bp抓包 3.添加poc username[#this.getClass().forName("java.lang.Runtime").getRuntime().exec("touch /tmp/zcc")]&password&repeatedPassword 4.…

红黑树:强大的数据结构之插入详解,附图

一、红黑树概述 红黑树是一种自平衡二叉查找树&#xff0c;具有以下性质&#xff1a;节点要么是红色要么是黑色&#xff1b;根节点是黑色&#xff1b;每个叶子节点&#xff08;NIL 节点&#xff09;是黑色&#xff1b;每个红色节点的两个子节点都是黑色&#xff1b;从任一节点到…

Matlab|考虑柔性负荷的综合能源系统低碳经济优化调度

目录 1 主要内容 2 部分代码 3 程序结果 4 下载链接 1 主要内容 程序主要实现的是考虑柔性负荷的综合能源系统低碳经济优化调度&#xff0c;模型参考《考虑柔性负荷的综合能源系统低碳经济优化调度》&#xff0c;求解方法采用的是混合整数规划算法&#xff0c;通过matlabc…

C++_23_STL容器

文章目录 STL容器概念常用容器A string作用构造函数基本赋值操作获取字符串长度存取字符操作拼接操作查找和替换注意:查找是不存在返回-1比较操作截取操作插入与删除string与char * 转换 B vector概述与数组区别迭代器构造函数赋值操作插入与删除取值操作大小相关存储自定义类型…

【逐行注释】扩展卡尔曼滤波EKF和粒子滤波PF的效果对比,MATLAB源代码(无需下载,可直接复制)

文章目录 总述源代码运行结果改进方向总述 本代码使用 M A T L A B MATLAB MATL</

用c++实现分数(fraction)类

这个想法已经有3周&#xff0c;于是今天将它实现了。 Step 1基础&#xff1a; 我们需要定义一个class——fraction&#xff0c;全部属性定义为public class fraction{ public:}; 现在&#xff0c;让我们添加2个元素&#xff0c;分子和分母——fz和fw Step 1.1添加分子分母…

Linux C++ 开发9 - 手把手教你使用gprof性能分析工具

1. 什么是gprof&#xff1f;2. gprof的用法 2.1. 编译程序2.2. 运行程序2.3. 生成分析报告2.4. gprof常用参数说明2.5. 分析报告解读 2.5.1. Flat profile 各个字段的含义2.5.2. Call graph 各个字段的含义 3. Demo演示 3.1. demo04.cpp 源码3.2. 编译、运行和分析3.3. 查看分…

快速搭建Kubernetes集群

快速搭建Kubernetes集群 1 MacOS 1.1 下载 从 docker 下载 docker-desktop (opens new window)&#xff0c;并完成安装 1.2 启用 k8s 集群 启动 docker-desktop&#xff0c;打开preference 面板 切换到 Kubernetes 标签页&#xff0c;并勾选启动 Enable Kubernetes&#xff0c;…

个人防护装备检测系统源码分享

个人防护装备检测检测系统源码分享 [一条龙教学YOLOV8标注好的数据集一键训练_70全套改进创新点发刊_Web前端展示] 1.研究背景与意义 项目参考AAAI Association for the Advancement of Artificial Intelligence 项目来源AACV Association for the Advancement of Computer…