public class Queue {
@Test
public void demo01(){
MyDeque myDeque = new MyDeque(10);
myDeque.enDeque(10);
myDeque.enDeque(11);
myDeque.enDeque(1);
myDeque.enDeque(2);
myDeque.enDeque(3);
myDeque.enDeque(7);
myDeque.enDeque(4);
myDeque.enDeque(5);
myDeque.enDeque(6);
myDeque.enDeque(8);
myDeque.enDeque(9);
for(int i = 1;i<13;i++){
myDeque.deDeque();
System.out.println(myDeque.maxvalue);
}
}
}
class MyDeque{
int[] deque;
int size;
// 因为要获取到最大值,所以在插入的时候进行存储,在删除的时候进行更改
int maxvalue = 0;
public MyDeque(){
deque = new int[10];
this.size = 0;
}
public MyDeque(int size){
deque = new int[size];
this.size = 0;
}
// 入队
public void enDeque(int element){
if(element > maxvalue){
maxvalue = element;
}
if(size >= deque.length){
dequeAppendSize(size * 2);
}
deque[deque.length - size -1] = element;
size +=1;
}
// 动态扩容
private void dequeAppendSize(int resize){
int[] copy = new int[resize];
for(int i = deque.length-1;i>=0;i--){
resize = resize-1;
copy[resize]=deque[i];
}
deque = copy;
}
// 出队
public int deDeque(){
if (size == 0){
System.out.println("队列为空");
return Integer.MAX_VALUE;
}
int copyEndValue = deque[deque.length-1];
int tempmax = deque[deque.length - 2];
for(int i = deque.length-1;i >= deque.length-1-size;i--){
tempmax = tempmax > deque[i - 1] ? tempmax : deque[i-1];
deque[i] = deque[i-1];
}
maxvalue = tempmax;
size = size - 1;
return copyEndValue;
}
}
设计一个队列 O(1) 均摊分析
最新推荐文章于 2021-07-04 16:17:36 发布