AlgorithmsI PA2: Randomized Queues and Deques Subset

时间:2021-11-01 23:00:16

AlgorithmsI PA2: Randomized Queues and Deques  Subset

AlgorithmsI PA2: Randomized Queues and Deques  Subset

本题的bonus是

AlgorithmsI PA2: Randomized Queues and Deques  Subset

因此方法是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]); RandomizedQueue<String> queue = new RandomizedQueue<String>(); while(StdIn.hasNextLine() && !StdIn.isEmpty()) {
if(queue.size() < k) {
queue.enqueue(StdIn.readString());
}else {
break;
}
} for(int i = 0; i< k; i++) {
StdOut.println(queue.dequeue());
}
}
}