AlgorithmsI PA2: Randomized Queues and Deques RandomizedQueue

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

    }
}
时间: 2024-08-10 12:40:37

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

AlgorithmsI PA2: Randomized Queues and Deques Subset

本题的bonus是 因此方法是queue的size 达到了K, 就停止增加元素,保证queue.size() 最大时只有k. Java code: import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class Subset { public static void main(String[] args){ int k = Integer.parseInt(args[0]); Rand

Programming Assignment 2: Randomized Queues and Deques

问题详述:http://coursera.cs.princeton.edu/algs4/assignments/queues.html Dequeue. A double-ended queue or deque (pronounced "deck") is a generalization of a stack and a queue that supports inserting and removing items from either the front or the bac

PrincetonAlgorithm I - Assignment2 Deques and Randomized Queues

Programming Assignment2 - Deque and Randomized Queues Review Assignment Specification 课程笔记 Subtext: Modular Programming Stacks and Queues are fundamental data types Value: collection of objects Basic Operation: insert, remove, iterate. Difference: wh

算法导论第四版学习——习题二Deques and Randomized Queues

题目正文: http://coursera.cs.princeton.edu/algs4/assignments/queues.html 作业难点: 1.选择使用链表还是数组,将会是第一个问题,选择合适会减少很多工作量. 2.并行从RandomizedQueue中取两个枚举,这两个枚举必须是不一样的,所以有很多偷懒的“伪随机”是行不通的. 3.SubSet仅需K存储而不是N存储,即可实现.(这个我也没想到方法实现) 作业技巧: 1.可遍数组和邻接节点两种数据结构都已经给你了,你只要改改,基本上实

Algorithm Part I:Programming Assignment(2)

问题描述: Programming Assignment 2: Randomized Queues and Deques Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to g

Coursera Algorithms第二周编程任务

Programming Assignment 2: Deques and Randomized Queues Write a generic data type for a deque and a randomized queue. The goal of this assignment is to implement elementary data structures using arrays and linked lists, and to introduce you to generic

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 the blog. What I was really trying to get across was that immutable data structures were possible and not that hard; a full-on finger tree implementation

计算机程序设计艺术(第一卷) 基本算法 第3版pdf

下载地址:网盘下载 内容简介  · · · · · · <计算机程序设计艺术>系列著作对计算机领域产生了深远的影响.这一系列堪称一项浩大的工程,自1962年开始编写,计划出版7卷,目前已经出版了4卷.<美国科学家>杂志曾将这套书与爱因斯坦的<相对论>等书并列称为20世纪最重要的12本物理学著作.目前Knuth正将毕生精力投入到这部史诗性著作的撰写中.想了解本书最新信息,请访http://www-cs-faculty.stanford.edu/~knuth/taocp.h

Coursera Algorithms Programming Assignment 2: Deque and Randomized Queue

这次作业与第一周作业相比,稍微简单一些.有三个编程练习:双端队列(Deque)设计.随机队列(Randomized Queue)设计,还有一个排列组合类Permutation. 一.双端队列Deque 设计要求:A double-ended queue or deque (pronounced "deck") is a generalization of a stack and a queue that supports adding and removing items from e