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. 快速打出System.out.println("");

    sysout---->Alt+/--->System.out.println():

  2. 学点bootstrap

  3. Java-分页实例

    1.PageModel.java package com.javaweb; import java.util.List; public class PageModel<E> { priva ...

  4. RegistryKey 类

    表示 Windows 注册表中的项级节点. 此类是注册表封装. 继承层次结构 System.Object   System.MarshalByRefObject    Microsoft.Win32. ...

  5. 浅谈Android系统的图标设计规范

    http://homepage.yesky.com/89/11620089.shtml 目前移动平台的竞争日益激烈,友好的用户界面可以帮助提高用户体验满意度,图标Icon是用户界面中一个重要的组成部分 ...

  6. .Net 4.0 Convert Object to XDocument

    将Object转换为XDocment对象 代码如下: C# – Object to XDocument using System; using System.Collections.Generic; ...

  7. offie2010设置前两页和后面显示不同页码的方法

    1.在需要设置的第二页文档后面点击一下,让光标进入,再菜单上找到"页面布局"—“分栏符”—“下一页”(如图) 2.插入—页码—页面底端(如图) 3.点击页码附近的—“链接到前一页面 ...

  8. SGU 101.Domino (欧拉路)

    时间限制: 0.5 sec 空间限制: 4096 KB 描述 多米诺骨牌,一种用小的方的木块或其他材料,每个都被一些点在面上标记,这些木块通常被称为骨牌.每个骨牌的面都被一条线分成两个   方形,两边 ...

  9. 知识库系统confluence5.8.10 安装与破解

    一直对知识库体系很在意,设想这样的场景,公司历年的研发资料只要一个搜索,相关的知识点就全部摆在面前,任君取用,想一想就无限迷人,只是从10年开始,由于种种原因,终究没能好好研究一下.最近机缘巧合,可以 ...

  10. .NET 元数据

    1. 安装 ILDASM 工具 VS -- 外部工具 -- 添加 -- 命令行为:C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NET ...