PrincetonAlgorithm I - Assignment2 Deques and Randomized Queues

Programming Assignment2 - Deque and Randomized Queues Review

Assignment Specification

课程笔记

Subtext: Modular Programming

  • Stacks and Queues are fundamental data types
    • Value: collection of objects
    • Basic Operation: insert, remove, iterate.
    • Difference: which item do we move? -> Stack: LIFO(last in first out) Queue: FIFO(first in first out)
  • Client, implementation, interface
    • Client: program using operations defined in interface
    • Implementation: actual code implementing operations
    • Interface: description of data type, basic operations

Stack Programming API:

public class StackOfStrings
StackOfStrings() //create an empty stack
void push(String item)  //insert a new string onto stack
String pop() //remove and return the string most recently added
boolean isEmpty()  //is the stack empty?

linked-list implementation

//Attention: Stack have only one exit -> only one pointer is enough
/*Corner Cases:client add a null item -> IllegalArgumentExceptionremove() from empty stack -> NoSuchElementException
*/
public class StackOfStrings {private Node first;private class Node {String item;Node next;}public boolean isEmpty() {return first == null;}public StackOfStrings {Node first = null;}public void push(String item) {//Improve: add exception to deal with invalid operationNode oldfirst = first;first = new Node(); //Attention: must craete a new instance herefirst.item = item;first.next = oldfirst;}public String pop() {String item = first.item;first = first.next;return item;}

Proposition: Every operation takes constant time in the worst case. A stack with N items uses 40N bytes
Object overhead (16) + inner class extra overhead(8) + item reference (8) + next reference(8) = 40

array implementation

/*
Underflow: throw exception if pop from an empty stack
Overflow: use resizing array for array implementation
*/
public class FixedCapacityStackOfStrings {private String[] s;private int N = 0;public FixedCapacityStackOfStrings (int capacity) {s = new String[capacity];}public String pop() {//Attention: declare null pointer to avoid loitering so garbage collector can reclaim memoryString item = s[--N];s[N] = null;return item;}public void push(String item) {s[N++] = item;}public boolean isEmpty() {return n == 0;}
}
  • Resizing array
    • Problem: Require client to provide capacity does not implement API. Constructor should not have int input
    • Question: How to grow and shrink array?
    • Answer: grow: double shrink: quarter - > Why? ->
      • double array for grow-> cost of is Linear N + (2 + 4 + 8 + .... + N) ~ 3N Geometric sequence: Sn = (a1 - an * q) / 1 - q
      • quarter for shrink -> avoid thrashing push - pop - push - pop when sequence is full -> each operation takes time propotional to N
        1066857-20180512230715922-1186033800.png
        example of trace resizing array
//Note: array is between 25% and 100% full 
public class ResizingArrayStackOfStrings {private String[] s;public ResizaingArrayStackOfStrings() {s = new String[1];}public void push(String item) {if (N == s.length) resize (2 * s.length);s[N++] = item;}private void resize(int capacity) {//create a double size array, copy the element from the old String array, update the pointerString[] copy = new String[capacity];for (int i = 0; i < capacity; i++) {copy[i] = s[i];s = copy;}public String pop() {String item = s[--N];S[N] = null;if (N > 0 && N = s.length/4) resize(s.length / 2);return item;}
}
  • Queue Programming API
    • QueueOfStrings()
    • void enqueue(String item)
    • String dequeue()
    • boolean isEmpty()
      Same API with stack, only name changed
*linked list implementation
/*Attention: 
Queue has two exit, so it needs two pointers
*/
public class LinkedQueueOfStrings {public LinkedQueueOfStrings() {Node first, last;int N = 0;}private class Node {String item;Node next;}public boolean isEmpty() {return first == null;}//enqueue elements added to the last of the queuepublic void enqueue(String item) {Node oldlast = last; // here last already points to an exist instance//Create a totally new Nodelast = new Node();last.item = item;last.next = null;//linked back with the queueif (isEmpty()) {//there is only one element exist ->first = last;}else {oldlast.next = last;}}public String dequeue() {String item = first.item;first = first.next;if (isEmpty()) {last = null;}return item;}
}
  • Generic data types: autoboxing and unboxing
    • Autoboxing: Automatic cast between a primitive type and its wrapper
    Stack<Integer> s = new Stack<Integer>();
    s.push(17);  //s.push(Integer.valueOf(17));
    int a = s.pop();  //int a = s.pop().intValue();

在写代码的过程当中,心里需要有转换角色的意识,当你在实现一个API的时候,需要考虑的是
* 实现某个方法所要使用的数据结构,
* 调用方法 or 自己写方法,
* API的性能要求 -> 使用哪种算法可以满足要求 查找,插入,删除 时间 + 空间

  • Iterators
    • What is an Iterable?
    • What is an Iterator?
    public interface Iterator<Item> {boolean hasNext();Item next();
    }
    • Why make data structures Iterable ?
  • Java collections library
    List Interface. java.util.List is API for an sequence of items
    • java.util.ArrayList uses resizing array -> only some operations are effieient
    • java.util.LinkedList uses linked list -> only some operations are effieient
      tip: 不清楚library的具体实现的时候,尽量避免调用相关的方法。可能效率会很低。
  • Arithmetic expression evaluation
    ( 1 + ( ( 2 + 3 ) * ( 4 * 5 ) ) )
    Two-stack algorithm. 【E. W. Dijkstra】
    • value: push onto the value stack
    • Operator: push onto the operator stack
    • Left parenthesis: ignore
    • Right parenthesis: pop operator and two values; push the result of applying that operator to those values onto the operand stack

总结:
Stack的链表实现
Stack的数组实现(resize array)
Queue的链表实现
Queue的数组实现(resize array)

对于双向队列的理解有误,导致错误实现。
双向对别不应当是两个队列的水平叠加,见figure 1

sketch of the Deque

作业总结:

  1. 对于文件的读写基本操作命令不够熟悉
  2. 对于问题的定义 出现了没有搞清楚题目要求的现象,包括Deque的基本操作 以及Permutation 类当中,应当是读取全部数据,输出k个数据,而不是读取k个数据,输出全部数据的问题

转载于:https://www.cnblogs.com/kong-xy/p/9028179.html

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Android Studio】查看源码时提示“throw new RuntimeException(Stub!)”

如题…… 详细问题及解决方法&#xff1a;http://blog.csdn.net/u010917495/article/details/51234179 转载于:https://www.cnblogs.com/jaxer/p/7071431.html

TCP短连接产生大量TIME_WAIT导致无法对外建立新TCP连接的原因及解决方法—基础知识篇...

最近遇到一个线上报警&#xff1a;服务器出现大量TIME_WAIT导致其无法与下游模块建立新HTTP连接&#xff0c;在解决过程中&#xff0c;通过查阅经典教材和技术文章&#xff0c;加深了对TCP网络问题的理解。作为笔记&#xff0c;记录于此。 备注&#xff1a;本文主要介绍…

如何在Jupyter Notebook中使用Python虚拟环境

1、创建虚拟环境&#xff1a; condacreate-n 环境名 python版本号 例如创建一个叫做dl的虚拟环境,python版本为3.7&#xff1a; conda create -n dl python3.7 2、激活虚拟环境&#xff1a; conda activate 环境名 3、在虚拟环境中安装ipykernel (切记这一步是在对应的虚…

python分离文件名和路径_python 分离文件名和路径以及分离文件名和后缀的方法...

{"moduleinfo":{"card_count":[{"count_phone":1,"count":1}],"search_count":[{"count_phone":4,"count":4}]},"card":[{"des":"阿里云文件存储NAS是一个可共享访问&#xf…

JS基础入门篇( 一 )

1.JS存放在代码中的位置 1.JS写在行间 <div style"background-color: red;" onclick"alert(1)" >hello world</div> 优点&#xff1a;直接&#xff0c;简单 缺点&#xff1a;不方便复用和维护,不符合结构行为分离规范2.JS写在script ( 一般写在…

开源许可证,欢迎来到云时代

出品 | OSC开源社区&#xff08;ID&#xff1a;oschina2013)作者 | 唐建法前言开源许可证从最早的 GPL 开始&#xff0c; 逐渐演进到 GPLv2 和 v3&#xff0c;中间还有 Apache、MPL、AGPL、LGPL 等&#xff0c;但是近几年来有一批新的许可证的出现&#xff0c;引起了社区的一些…

15_新闻客户端_展示文字内容完成

1232131转载于:https://www.cnblogs.com/ZHONGZHENHUA/p/7074670.html

python socket传输图片_python使用socket传输图片视频等文件的实现方式

python使用socket传输图片视频等文件的实现方式来源&#xff1a;中文源码网 浏览&#xff1a; 次 日期&#xff1a;2019年11月5日【下载文档: python使用socket传输图片视频等文件的实现方式.txt 】(友情提示:右键点上行txt文档名->目标另存为)python 使用socket传输…

selenium - Select类 - 下拉框

WebDriver提供了Select类来处理下拉框。 如百度搜索设置的下拉框&#xff0c;如下图&#xff1a; from selenium import webdriver from selenium.webdriver.support.select import Select from time import sleepdriver webdriver.Chrome() driver.implicitly_wait(10) drive…

ubuntu安装samba

1 首先当然是要安装samba了&#xff1a;sudo apt-get install sambasudo apt-get install smbfs 2 下面我们来共享群组可读写文件夹&#xff0c;假设你要共享的文件夹为&#xff1a; /home/ray/sharemkdir /home/ray/sharechmod 777 /home/ray/share 备份并编辑smb.conf允许网络…

.NET 7 预览版 7

点击上方蓝字关注我们&#xff08;本文阅读时间&#xff1a;12分钟)今天我们发布了 .NET 7 预览版 7。这是 .NET 7 的最后一个预览版&#xff0c;下一个版本将是我们的第一个候选版本 &#xff08;RC&#xff09;。.NET Conf 2022 的日期已经公布&#xff01;请于 2022 年 11 月…

QWaiteCondition思考3

QWaitConditioin::wait() 接收一个mutex作为参数&#xff0c;这个mutex应该被调用线程初始化为锁定状态。在线程进入休眠状态&#xff08;waite&#xff09;之前&#xff0c;mutex会被解锁。当线程被唤醒&#xff08;WakeOne/wakeAll)时&#xff0c;mutex会处于锁定状态。而且&…

python实现定时任务的方式_Python实现定时执行任务的三种方式简单示例

本文实例讲述了Python实现定时执行任务的三种方式。分享给大家供大家参考&#xff0c;具体如下&#xff1a;1.定时任务代码#!/user/bin/env python# Time :2018/6/7 16:31# Author :PGIDYSQ[email protected] :PerformTaskTimer.py#定时执行任务命令import time,os,schedschedu…

js 获取data-属性值

// html code <span class"1pc_price" data-price"<?php echo Country::change($29.95,$money_type) . "<br/>Download Instantly"; ?>"></span>// js codevar price_1pc_hb document.getElementsByClassName(1pc_p…

android--------volley之网络请求和图片加载

为什么80%的码农都做不了架构师&#xff1f;>>> Volley是 Google 推出的 Android 异步网络请求框架和图片加载框架。 Volley的特性 封装了的异步的请求API。Volley 中大多是基于接口的设计&#xff0c;可配置性强。一个优雅和稳健的请求队列&#xff0c;一定程度符…

经典算法学习——冒泡排序

冒泡排序是我们学习的第一种排序算法。应该也算是最简单、最经常使用的排序算法了。无论怎么说。学会它是必定的。今天我们就用C语言来实现该算法。演示样例代码已经上传至&#xff1a;https://github.com/chenyufeng1991/BubbleSort算法描写叙述例如以下&#xff1a;&#xff…

Mybatis之设计模式之装饰者模式

了解&#xff0c;什么是装饰者模式? 1.定义 装饰模式是在不必改变原类文件和使用继承的情况下&#xff0c;动态地扩展一个对象的功能。它是通过创建一个包装对象&#xff0c;也就是装饰来包裹真实的对象。 2.特点 1 装饰对象和真实对象有相同的接口。这样客户端对象就能以和真…

python求非线性优化问题_用python优化非线性函数

我在python中有一个函数&#xff0c;如下所示&#xff1a;import numpy as npdef fun(Gp,Ra,Mr,Pot,Sp,Mc,Keep):if(KeepTrue):return(Pot*np.tanh((GpRaMr Mc)*Sp ))假设以下数据&#xff1a;^{2}$我总共有100个GP&#xff0c;我想适当地分配它们为了最大化objective_function…

一天掌握Android JNI本地编程 快速入门

一、JNI&#xff08;Java Native Interface&#xff09; 1、什么是JNI&#xff1a;JNI(Java Native Interface):java本地开发接口JNI是一个协议&#xff0c;这个协议用来沟通java代码和外部的本地代码(c/c) 外部的c/c代码也可以调用java代码2、为什么使用JNI&#xff1a;效率上…

轻量级ORM框架PetaPoco

1、简介PetaPoco是一个小型、快速、单文件的微型ORM&#xff08;Object Relational Mapper&#xff09;框架&#xff0c;可在.NET和Mono环境运行。https://github.com/CollaboratingPlatypus/PetaPoco2、特点PetaPoco 是一个用于 .NET 的小型且快速的微型 ORM与Dapper一样&…