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.
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的更多相关文章
- AlgorithmsI PA2: Randomized Queues and Deques Subset
本题的bonus是 因此方法是queue的size 达到了K, 就停止增加元素,保证queue.size() 最大时只有k. Java code: import edu.princeton.cs.al ...
- AlgorithmsI PA2: Randomized Queues and Deques Deque
本次作业考察利用array 或者linked list 实现规定时间复杂度的queue 和stack, 不能使用java 自带的stack 和queue. 目的是让我们掌握自己设计的函数的复杂度. D ...
- Programming Assignment 2: Randomized Queues and Deques
实现一个泛型的双端队列和随机化队列,用数组和链表的方式实现基本数据结构,主要介绍了泛型和迭代器. Dequeue. 实现一个双端队列,它是栈和队列的升级版,支持首尾两端的插入和删除.Deque的API ...
- Programming Assignment 2: Deques and Randomized Queues
编程作业二 作业链接:Deques and Randomized Queues & Checklist 我的代码:Deque.java & RandomizedQueue.java & ...
- Deques and Randomized Queues
1. 题目重述 完成三个程序,分别是双向队列,随机队列,和随机队列读取文本并输出k个数. 2. 分析 2.1 双向队列 题目的性能要求是,操作时间O(1),内存占用最大48n+192byte. 当使用 ...
- 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 ...
- Java 性能调优指南之 Java 集合概览
[编者按]本文作者为拥有十年金融软件开发经验的 Mikhail Vorontsov,文章主要概览了所有标准 Java 集合类型.文章系国内 ITOM 管理平台 OneAPM 编译呈现,以下为正文: 本 ...
- Coursera Algorithms Programming Assignment 2: Deque and Randomized Queue (100分)
作业原文:http://coursera.cs.princeton.edu/algs4/assignments/queues.html 这次作业与第一周作业相比,稍微简单一些.有三个编程练习:双端队列 ...
- [LeetCode] Implement Stack using Queues 用队列来实现栈
Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...
随机推荐
- spring mvc DispatcherServlet详解之三---request通过ModelAndView中获取View实例的过程
整个spring mvc的架构如下图所示: 上篇文件讲解了DispatcherServlet第二步:通过request从Controller获取ModelAndView.现在来讲解第三步:reques ...
- camera理论基础和工作原理
写在前面的话,本文是因为工作中需要编写摄像头程序,因为之前没有做过这类产品,所以网上搜索的资料,先整理如下,主要参考文章如下,如果有侵权,请联系我:另外,转载请注明出处.本文不一定全部正确,如果发现错 ...
- Android read-only file system解决方法
adb shell su - mount -o rw,remount /system
- Android(java)学习笔记204:自定义SmartImageView(继承自ImageView,扩展功能为自动获取网络路径图片)
1.有时候Android系统配置的UI控件,不能满足我们的需求,Android开发做到了一定程度,多少都会用到自定义控件,一方面是更加灵活,另一方面在大数据量的情况下自定义控件的效率比写布局文件更高. ...
- webservice 发布到外网的时候
在web.config的<system.web></system.web>中间加入如下配置节内容<webServices> <protoco ...
- 关于ajaxfileupload.js一些问题和上传图片就立即显示图片功能
ajaxfileupload.js是上传文件的一个插件,最近碰到的一个问题是在谷歌浏览器上传文件之后,原文本框中的文件名称消失,网上搜了好长时间也没有十分满意的答案.无刷新上传文件我想到的只有ajax ...
- C#超时处理(转载)
/// <summary> /// 超时处理 /// /// /// </summary> public class TimeoutChecker ...
- ratingBar抢焦点问题
ratingBar抢viewpager焦点问题: 1)写一个类继承ratingBar,让onTouchevent或者dispatchTouchEvent返回false 2)设置ratingBar的属性 ...
- 非常不错的ASP操作数据库类,支持多数据库MSSQL,ACCESS,ORACLE,MYSQL等
可同时操作多个不同类型的数据库. 完全不用考虑数据类型的差别,再也不用想字符型字段加不加单引号. 调用非常简单,对数据库的主要操作一般只需要一行代码. 支持mssql事务回滚. 可自动生成和输出sql ...
- 【转】 iOS KVO KVC
原文: http://www.cocoachina.com/industry/20140224/7866.html Key Value Coding Key Value Coding是cocoa的一个 ...