Week 2
Queue with Two Stacks
原题
Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.
分析
用两个栈实现一个队列,就是用LIFO性值转化成FIFO
思路
一个栈负责进,一个栈负责出,入队时push到进栈,出队时从出栈pop,如果此使出栈是空的,就把当前进栈所有的元素全部按顺序pop并push到出栈中
Stack with Max
原题
Create a data structure that efficiently supports the stack operations (push and pop) and also a return-the-maximum operation. Assume the elements are reals numbers so that you can compare them.
分析
在实现栈的功能的同时能够返回当前栈中的最大值
思路
(这个题的提示貌似有问题,用栈不知道怎么维护最大值)可以使用两种方法,第一种就是直接遍历,线性时间也是可以接受的;另一种是维护一个二叉排序树,log时间更理想,但是这里还没弄明白怎么删节点,应该会比较麻烦(左子树最右节点或者右子树最左节点)
Java Generics
原题
Explain why Java prohibits generic array creation.
分析
Java核心知识
思路
根据提示,Java的数组是协变的,但是泛型不是协变的
对Java数组,泛型会在编译时抹去详细类型信息,这将会导致其无法在运行时执行类型安全检查
Intersection of two sets
原题
Given two arrays a [ ] \mathtt{a[]} a[] and b [ ] \mathtt{b[]} b[], each containing n n n distinct 2D points in the plane, design a subquadratic algorithm to count the number of points that are contained both in array a [ ] \mathtt{a[]} a[] and array b [ ] \mathtt{b[]} b[].
分析
求两个集合的交集,但是要求次二次时间复杂度
思路
使用shellsort对两个集合内元素排序,从第一个元素开始,判断a[i]
和b[j]
,如果二者相等,计数器加一,i
和j
同时加一;如果前者大,后者索引加一,如果后者大,前者索引加一,直到其中一方遍历完全部元素
Permutation
原题
Given two integer arrays of size n n n, design a subquadratic algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
分析
判断两个集合是否互为排列,但是要求次二次时间复杂度
思路
和上一题一样,先排序,然后审查对应的全部元素,要求所有元素按顺序完全相同
##Dutch national flag
原题
Given an array of n n n buckets, each containing a red, white, or blue pebble, sort them by color. The allowed operations are:
- s w a p ( i , j ) swap(i, j) swap(i,j): swap the pebble in bucket i i i with the pebble in bucket j j j.
- c o l o r ( i ) color(i) color(i): determine the color of the pebble in bucket i i i.
The performance requirements are as follows:
- At most n n n calls to c o l o r ( ) color() color().
- At most n n n calls to s w a p ( ) swap() swap().
- Constant extra space.
分析【非原创】
就是要求在线性时间内将三色小球按颜色归类,红色在左,白色在中,蓝色在右
思路
三路快排,将在第三周讲授