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. iOS-C文件添加到iOS项目中,运行报错

    iOS-C文件添加到iOS项目中,运行报错 问题: 往项目中添加一个空的c文件, 编译运行; 出现2,30个编译错误. 原因: 由于在项目中添加了Pch文件,在文件中所有代码还没有开始运行之前, pc ...

  2. iOS中__block 关键字的底层实现原理

    在 <iOS面试题集锦(附答案)> 中有这样一道题目: 在block内如何修改block外部变量?(38题)答案如下: 默认情况下,在block中访问的外部变量是复制过去的,即:写操作不对 ...

  3. 如何在windows/wamp环境下在本机配置站点

    1. 在D:\wamp\bin\apache\Apache2.5.4\conf文件夹下,找到httpd.conf,使用记事bej打开它,搜索#Include conf/extra/httpd-vhos ...

  4. 发现并认为这是jQuery1.4.4的一个Bug

    说起来还觉得丢人,公司的系统开发了两年,目前jquery的版本还是用的1.4.4. mantis上的Bug一堆,今天在改bug的时候发现一个jQuery的Bug. 改bug嘛,一开始总是各种调试,总感 ...

  5. oracle 里面定时执行任务,比如存储过程内容等。

    DECLARE   job_no_ NUMBER;   BEGIN      DBMS_JOB.SUBMIT(job_no_,                   'proc_qszx_dw_sc(' ...

  6. UITapGestureRecognizer会屏蔽掉Button的点击事件( 转载)

    UITapGestureRecognis 前几天在做项目的时候,遇到这个一个问题,在一个视图也就是UIView上添加一个手势,然后又在这个View上添加一个UIButton,然后给按钮添加事件,运行项 ...

  7. Facade 模式

    在软件系统开发中经常回会遇到这样的情况,你实现了一些接口(模块),而这些接口(模块)都分布在几个类中(比如 A和 B.C.D) :A中实现了一些接口,B 中实现一些接口(或者 A代表一个独立模块,B. ...

  8. SGU 121.Bridges painting

    原题地址 题意: 新百慕大由N个岛屿组成,在岛屿之间有一些连接它们的桥.在任意两个岛屿之间,最多只有一座桥连接它们.总统先生下达命令,要求给所有桥上色. 每一座桥能被染成 白色 或者 黑色. 每一个岛 ...

  9. SGU 132.Another Chocolate Maniac

    时间限制:0.25s 空间限制:4M 题目: Bob非常喜欢巧克力,吃再多也觉得不够.当他的父母告诉他将要买很多矩形巧克力片为他庆祝生日时,他的喜悦是能被理解的.巧克力都是 2x1 或 1x2 的矩形 ...

  10. extern "C" {} 来沟通C和C++

    比如说你用C++开发了一个DLL库,为了能够让C语言也能够调用你的DLL输出(Export)的函数,你需要用extern "C"来强制编译器不要修改你的函数名. 通常,在C语言的头 ...