RandomizedQueue 有几个关键点:

1. 选择合适的数据结构,因为需要任意位置删除元素,Linked list 做不到,必须使用resizing arrays.

2. resizing 的技巧。

Q. How to grow array?
    A. If array is full, create a new array of twice the size, and copy items.

    Q. How to shrink array?

    A: halve size of array when array is one-quarter full 
3. 正确使用StdRandom.shuffle. 要能实现并行使用Iterator,洗牌不是洗array 本身,而是生成一个乱序的index. 

Java code:
//RandomizedQueue - should be implemented using resizing arrays
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import java.util.Iterator;
import java.util.NoSuchElementException; public class RandomizedQueue<Item> implements Iterable<Item> {
private Item[] q; // array of items
private int N; // number of elements // construct an empty randomized queue
public RandomizedQueue() {
q = (Item[]) new Object[1];
N = 0;
} // is the queue empty?
public boolean isEmpty() {
return N == 0;
} // return the number of items on the queue
public int size() {
return N;
} // resize the underlying array holding the elements
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = q[i];
}
q = temp;
} // add the item
//Throw a java.lang.NullPointerException if the client attempts to add a null item
public void enqueue(Item item) {
if(item == null) {
throw new NullPointerException("add a null item");
}
if(N == q.length) {
resize(2 * q.length); // double size of array if necessary
}
q[N++] = item; // add item
} /*when deleting random element you can just simply switch it with the last element in array
* and decrease the array size counter. So deletion will take constant time.
*throw a java.util.NoSuchElementException if the client attempts to sample or dequeue an item
*from an empty randomized queue;
*/
// remove and return a random item
public Item dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("No element");
}
int x = StdRandom.uniform(N);
Item item = q[x];
q[x] = q[--N];
q[N] = null; if (N == q.length / 4 && N > 0) {
resize(q.length / 2);
}
return item;
} // return (but do not remove) a random item
public Item sample() {
if(isEmpty()) {
throw new NoSuchElementException("No element");
}
int x = StdRandom.uniform(N);
return q[x];
} // return an independent iterator over items in random order
public Iterator<Item> iterator() {
return new ArrayIterator();
} private class ArrayIterator implements Iterator<Item> {
private int i;
private int[] indexSequence; public ArrayIterator() {
i = 0;
indexSequence = new int[N];
for (int j = 0; j < N; j++) {
indexSequence[j] = j;
}
StdRandom.shuffle(indexSequence);
} public boolean hasNext() {
return i < N ;
}
public void remove() {
throw new UnsupportedOperationException();
} public Item next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return q[indexSequence[i++]];
}
} public static void main(String[] args) { // unit testing }
}

AlgorithmsI PA2: Randomized Queues and Deques RandomizedQueue的更多相关文章

  1. AlgorithmsI PA2: Randomized Queues and Deques Subset

    本题的bonus是 因此方法是queue的size 达到了K, 就停止增加元素,保证queue.size() 最大时只有k. Java code: import edu.princeton.cs.al ...

  2. AlgorithmsI PA2: Randomized Queues and Deques Deque

    本次作业考察利用array 或者linked list 实现规定时间复杂度的queue 和stack, 不能使用java 自带的stack 和queue. 目的是让我们掌握自己设计的函数的复杂度. D ...

  3. Programming Assignment 2: Randomized Queues and Deques

    实现一个泛型的双端队列和随机化队列,用数组和链表的方式实现基本数据结构,主要介绍了泛型和迭代器. Dequeue. 实现一个双端队列,它是栈和队列的升级版,支持首尾两端的插入和删除.Deque的API ...

  4. Programming Assignment 2: Deques and Randomized Queues

    编程作业二 作业链接:Deques and Randomized Queues & Checklist 我的代码:Deque.java & RandomizedQueue.java & ...

  5. Deques and Randomized Queues

    1. 题目重述 完成三个程序,分别是双向队列,随机队列,和随机队列读取文本并输出k个数. 2. 分析 2.1 双向队列 题目的性能要求是,操作时间O(1),内存占用最大48n+192byte. 当使用 ...

  6. The Swiss Army Knife of Data Structures … in C#

    "I worked up a full implementation as well but I decided that it was too complicated to post in ...

  7. Java 性能调优指南之 Java 集合概览

    [编者按]本文作者为拥有十年金融软件开发经验的 Mikhail Vorontsov,文章主要概览了所有标准 Java 集合类型.文章系国内 ITOM 管理平台 OneAPM 编译呈现,以下为正文: 本 ...

  8. Coursera Algorithms Programming Assignment 2: Deque and Randomized Queue (100分)

    作业原文:http://coursera.cs.princeton.edu/algs4/assignments/queues.html 这次作业与第一周作业相比,稍微简单一些.有三个编程练习:双端队列 ...

  9. [LeetCode] Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

随机推荐

  1. windows和linux双系统删除linux

    装了Windows和linux双系统的朋友,在后期要删除linux是个比较头痛的问题,因为MBR已经被linux接管,本文的目的是如何在windows 和linux双系统下,简单,完美地卸载linux ...

  2. Linux Device Driver 3th 中的一些坑

    linux设备驱动第三版由于年代比较久远,有很多东西已过时.开一贴记录自己发现的一些问题. 4.3.1.4. seq_file接口 此节最后提到用 struct proc_dir_entry* cre ...

  3. Android(java)学习笔记206:利用开源SmartImageView优化网易新闻RSS客户端

    1.我们自己编写的SmartImageView会有很多漏洞,但是我们幸运的可以在网上利用开源项目的,开源项目中有很多成熟的代码,比如SmartImageView都编写的很成熟的 国内我们经常用到htt ...

  4. python s12 day3

    python s12 day3   深浅拷贝 对于 数字 和 字符串 而言,赋值.浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...

  5. hibernate中使用HQL进行数据库查询

    1.写的规则比较简单,我讲一下,如图Station这个不是数据库中的表,而是entity包中的类名Station,可以省略 select * 2.返回的类型自动转化为String类型,不用你自己再转化 ...

  6. LENGTH和LENGTHB函数,substrb截取也是同一个道理。

    oracle 利用 LENGTH和LENGTHB函数区分中英文(2009-02-07 10:49:29) 转载▼ 标签: it 分类: oracle 前一段时间,我一朋友问我怎么得出这个字符串是中文还 ...

  7. ActionScript:Resampling PCM data

    使用基于flash的麦克风录音,如果想在获取完PCM采样数据后,通过Sound马上回放,必须经过resampling.(注意:如果录音是采用的44KHz的话,则不需要) 因此,需要as实现一个简便的函 ...

  8. winform降低功耗总结

    这里整理了一些网上关于Winform如何降低系统内存占用的资料,供参考: 1.使用性能测试工具dotTrace 3.0,它能够计算出你程序中那些代码占用内存较多2.强制垃圾回收3.多dispose,c ...

  9. 初识sass框架

    编写过页面的开发者都知道css这个东西,究其原意,也就是层叠样式表,我们页面的三大结构,html css javascript,其中html负责主要的页面结构,css就负责主要的页面样式,而我们的js ...

  10. MATLAB中mexFunction函数的接口规范

    MEX文件的调用极为方便,其调用方式与MATALAB的内建函数完全相同,只需要在命令窗口内输入对应的文件名称即可. C语言MEX程序代码文件有计算子例程(Computational routine)和 ...