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. block没那么难(二):block和变量的内存管理

    本系列博文总结自<Pro Multithreading and Memory Management for iOS and OS X with ARC> 了解了 block的实现,我们接着 ...

  2. Css实现透明效果,兼容IE8

    Css实现透明效果,兼容IE8 >>>>>>>>>>>>>>>>>>>>> ...

  3. 表达式:使用API创建表达式树(3)

    一.DebugInfoExpression:发出或清除调试信息的序列点. 这允许调试器在调试时突出显示正确的源代码. static void Main(string[] args) { var asm ...

  4. EF6.0+Mysql的问题

    最近在项目中使用EF for Mysql的时候遇到一个问题 public OrderManage GetOrders(OrderSearchCriteria criteria) { using (va ...

  5. VS2015 Cordova Ionic移动开发(三)

    一.基础设置 1.修改App名称和程序起始页 打开config.xml配置文件显示如下,在[通用]选项卡中,将显示名称和起始页,修改为自己想要的名称即可. 如需直接在xml文件中修改:右击config ...

  6. 国际化 native2ascii用法

    cmd下输入: native2ascii -encoding GBK(需要编译成哪种语言) (中文文件路劲) (英文文件路劲) 其他固定 例如 native2ascii -encoding GBK C ...

  7. php输出echo、print、print_r、printf、sprintf、var_dump的区别比较

    本篇文章是对php输出echo.print.print_r.printf.sprintf.var_dump的区别进行了详细的分析介绍,需要的朋友参考下     用.net开发已经5年了,最近突然想接触 ...

  8. WordPress4.1新的函数介绍

    wordpress 4.1也更新了一阵子了,作为一般用户最关系的就是新的wordpress主题,作为开发者,新增的函数也给我们带来了更多的便捷和惊喜,今天就转载一篇介绍wordpress4.1中新增的 ...

  9. Tomcat 8熵池阻塞变慢详解(转)

    Tomcat 8熵池阻塞变慢详解 作者:chszs,转载需注明.博客主页:http://blog.csdn.net/chszs Tomcat 8启动很慢,且日志上无任何错误,在日志中查看到如下信息: ...

  10. 网络编程(学习整理)---2--(Udp)实现简单的控制台聊天室

    1.UDP协议: 总结一下,今天学习的一点知识点! UDP也是一种通信协议,常被用来与TCP协议作比较!我们知道,在发送数据包的时候使用TCP协议比UDP协议安全,那么到底安全在哪里呢?怎么理解呢! ...