我需要实现一个队列,理想情况下是使用Java。它必须在固定时间内实现方法void push(int value)
,int pop()
和int peek(int index)
。
请注意,对于push(),我们输入了一个值,而对于peek(),我们输入了一个索引。
我已经设法通过使用圆形数组在恒定时间内实现推送,弹出和窥视。对于流行我返回头。为了推动,我把尾巴放进去了。窥视一下,我只是在传递的索引处返回数组中的元素。
我的问题:如果数组的大小不固定,如何在恒定时间内推送新元素,同时又保持其他2个fxns不变?您必须增加阵列的大小。那你怎么办呢?
我在代码中有2个问题被写为注释;请同时回答这两个问题,并提供代码审查!
也请帮助我在下面的代码中解决此注释:/ 我想找到“是否(索引不在头尾之间)”的一种方法是通过从头到尾循环循环并确保索引出现。为了确定恒定的时间,一种想法是随您添加arr中的所有索引到集合中。还有其他恒定时间的想法吗? /
代码:
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
Queue q = new Queue();
}
public static class Queue<Integer> {
//capacity == arr.length
private int capacity;
private int head;
private int tail;
private int[] arr;
private int size;
public Queue () {
capacity = 16;
head = tail = 0;
arr = new int[capacity]; //0-15
size = 0;
}
public void push(int value) {
tail = (tail + 1) % capacity;
//alternatively can look to use 'if (size == capacity)'
if (tail == head) {
resize(); //not constant time when we're @ capacity; help!!
}
arr[tail] = i;
size++;
}
private void resize() {
int[] temp = new int[2 * capacity];
int index = head;
//arr.length == capacity
for (int i = 0; i < capacity; i++) {
temp[i] = arr[index];
index = (index + 1) % capacity;
}
arr = temp;
head = 0;
tail = capacity + 1;
this.capacity = capacity * 2;
}
public int pop() throws Exception{
if (size == 0) {
throw new EmptyQueueException();
}
int oldHead = head;
head = (head + 1) % capacity;
size--;
return oldHead;
}
public int peek(int index) {
/*one way I can think to find 'if (index not between head and tail)' is by looping circularly from head to tail and ensuring that index appears. to determine in constant time, 1 idea is to add all indicies in arr to a set as you go. any other constant time ideas?*/
if (index not between head and tail) {
throw new IllegalArgumentException();
}
return arr[index];
}
}
}