Princeton Alogorithm COS 226 Week2 Stack Queue

Interface

there are a lot of benefits when we use interface to programming not class.
Client has many implementation for this interface from which choose the best suitable one. As we know List is a famous interface in java collections. so we have linked list which have good performance when insert at front. and we have array list implementation which random get is O (1).

when programmer do implementation, they can not know details of client need.

stack implementation

below picture is described how to use linkedlist to implement stack. stack also could be implemented by array.


image.png

image.png

below is array implementation


image.png

and we need to care two edge case. one is overflow, one is underflow.
overflow means array is full, we need to resize it. underflow means client pop on an empty array, we need to throw exception or return null.

so the next question is that how to resize?


image.png

how to shrink array?
if we halve size of array when array is one-half full.
it is terrible consider push - pop - push -pop when array is full
each operation takes time proportional to N


image.png

so now the stack have two implementation. when should we choose array, when should we choose linkedlist
if u want to make every operation time is little in the worst case. i mean even if one operation is cost too many time is disaster, u should choose linked list.

array implentation have good memory usage and good performance on amortized time. but sometimes when need to expand/resize, that operation will cost more time than regular ones.

Queue

queue is almost same as stack, except it is fifo, stack is lifo.

Generic

image.png

java generic have two benefits.
one is avoid casting in client, another is discover type mismatch in compile time instead of run time.

Autoboxing

image.png

Iterators

image.png

Bag

image.png

Quiz analysis

Q1

image.png

the stack is lifo, queue is fifo. when we want to out, we need to reverse elements in stack. so that's the usage of second stack.

Q2

image.png

the naive though for this problem, we keep two stack, one is original, another is keep the current max.

we can do better, because there are a lot of data redundancy in second stack.
we can only record the one which make the max changed idx.
then if we pop to that idx, we need to pop from max stack.
for example,
stack : 1,1,2,2,3
max val: 1,2,3
max idx, 0,2,4

Q3

Java generics. Explain why Java prohibits generic array creation.

first, java array are covariant, but java generic are not

Each object in Java has a "class" which can be retrieved at runtime, using the .getClass() method. When you use .getClass() on an array object, you get the "array class" representing that type of array. Arrays of different component types correspond to different array classes. So .getClass() called on an int array will return a different thing than .getClass() called on a String array. From any array object, we can query its (array) class at runtime, and then from that, get the component type of the array. That is what I meant that the array remembers its component type at runtime.

How does an object know its class? That's because it was provided explicitly when the object was created. The same applies for array objects. When you create an array, you must specify the type of array, including an explicit component type. However, Generic types in code are a compile-time illusion. When you have a type variable like T, code that uses that type cannot know what type T is; and in fact, the point is that the code must work with any type in the place of T. That is why the class or method is said to be "generic". That is what I meant when I said T represents a type that is unknown at runtime, and thus you cannot create an array of T since you cannot provide the component type needed to create the array.

Note that this contrasts with Generic containers. For example, new ArrayList<T>() is perfectly legal. You might ask, why is it possible to create a List of T, but not possible to create an array of T? Generic types in Java work very differently from array types. A new ArrayList<Integer>() object and new ArrayList<String>() object have the same "class" at runtime. That is, the type parameter is an illusion and it is not possible to tell at runtime whether a list is a list of String or list of Integer. Therefore, such containers do not know their component type at runtime; and correspondingly it is not necessary to know the component type at runtime to create such a container object.

Q4

Implement a deque with two stacks so that each deque operations takes a constant amortized number of stack operations

the thought is similar with the two stack implementing queue. we keep two stack, one the open for left, another is open for right. so offer first, go left stack, offer last, go right stack.

the hardest part is poll first or poll right when the left stack or right stack empty
we need to do a rebalance action like the Q1, we keep another auxiliary stack, to move half elements of not empty stack into it then move another half to the empty stack. then we move the auxiliary stack back.

Project Deques and Randomized Queues

https://coursera.cs.princeton.edu/algs4/assignments/queues/specification.php

this week project we can practice generic, interface. a lot of point in course mentioned u have a chance to practice.

for deque, i use linked list to implement and also i use dummy node to reduce the complexity of the code. the important thing is u not only need to implement correctness algorithm for this data structure but also handle edge case. i mean sometimes the client use your data structure in wrong way. u should mention them.

for randomized queue, i use array to implement, so we have to implement resize function to handle when the queue is full.

Bonus

the bonus on the permutation is that could we use only O(k) space to finish it.

let think from k = 1. how to use O 1 space to get random one value.
we keep a output value. first it should be the first element. then next element will have 1/2 chance to replace this output value. the third element will have 1/3 chance to replace output value

at now, the first element will have 1 * 1/2 * 2/3 = 1/3 in the output value
the second element will have 1/2 * 2/3 = 1/3
the third element will have 1/3
they are the same

so how to expand this algorithm to K elements.

assume k is 2, total element is 3, so we want each element have 2/3 chance in the result.
at first we put 2 element in randomized queue.
the next element will have 2/3 chance to replace one of element in queue
now the problem solve

so we can get the formula
first we put k element in randomized queue. then the next element we have k/i to replace it in the randomized queue. i is the index of i th element start from 1

take N =5, k= 3 as example
first put 1st, 2nd, 3rd into random queue
the 4th have 3/4 chance to replace one of them
the 5th have 3/5 chance to replace one of them

the 1st have 1 * (2/3 * 3 /4 + 1/4) * (2/3 * 3/5 + 2/5) = 3/5 in the queue
u can calculate by yourself for other elements.

course quiz and project : https://github.com/yixuaz/algorithm4-princeton-cos226

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,163评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,301评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,089评论 0 352
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,093评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,110评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,079评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,005评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,840评论 0 273
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,278评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,497评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,667评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,394评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,980评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,628评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,796评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,649评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,548评论 2 352

推荐阅读更多精彩内容