題目描述:
設計實作雙端隊列。
你的實作需要支援以下操作:
MyCircularDeque(k):構造函數,雙端隊列的大小為k。
insertFront():将一個元素添加到雙端隊列頭部。 如果操作成功傳回 true。
insertLast():将一個元素添加到雙端隊列尾部。如果操作成功傳回 true。
deleteFront():從雙端隊列頭部删除一個元素。 如果操作成功傳回 true。
deleteLast():從雙端隊列尾部删除一個元素。如果操作成功傳回 true。
getFront():從雙端隊列頭部獲得一個元素。如果雙端隊列為空,傳回 -1。
getRear():獲得雙端隊列的最後一個元素。 如果雙端隊列為空,傳回 -1。
isEmpty():檢查雙端隊列是否為空。
isFull():檢查雙端隊列是否滿了。
示例:
MyCircularDeque circularDeque = new MycircularDeque(3); // 設定容量大小為3
circularDeque.insertLast(1); // 傳回 true
circularDeque.insertLast(2); // 傳回 true
circularDeque.insertFront(3); // 傳回 true
circularDeque.insertFront(4); // 已經滿了,傳回 false
circularDeque.getRear(); // 傳回 2
circularDeque.isFull(); // 傳回 true
circularDeque.deleteLast(); // 傳回 true
circularDeque.insertFront(4); // 傳回 true
circularDeque.getFront(); // 傳回 4
提示:
所有值的範圍為 [1, 1000]
操作次數的範圍為 [1, 1000]
請不要使用内置的雙端隊列庫。
使用一個數組,每次往頭部插入時将所有的元素往後移,然後插入0,用一個索引記錄目前的數量
class MyCircularDeque {
int []deque;
int indexstart = 0;
int indexend = 0;
/** Initialize your data structure here. Set the size of the deque to be k. */
public MyCircularDeque(int k) {
deque = new int[k];
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
public boolean insertFront(int value) {
// 表示已經滿了
if(indexend == deque.length){
return false;
}else {
int [] tem = Arrays.copyOf(deque, deque.length);
tem[0] = value;
for (int i = 1; i < tem.length; i++) {
tem[i] = deque[i-1];
}
deque = Arrays.copyOf(tem, deque.length);
indexend ++;
return true;
}
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
public boolean insertLast(int value) {
if(indexend == deque.length){
return false;
}else {
deque[indexend] = value;
indexend ++;
return true;
}
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
public boolean deleteFront() {
if(indexend == 0){
return false;
}else {
for (int i = 1; i < indexend; i++) {
deque[i-1] = deque[i];
}
indexend --;
return true;
}
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
public boolean deleteLast() {
if(indexend != 0){
indexend --;
return true;
}else {
return false;
}
}
/** Get the front item from the deque. */
public int getFront() {
if(indexend != 0){
return deque[0];
}else {
return -1;
}
}
/** Get the last item from the deque. */
public int getRear() {
if(indexend != 0){
return deque[indexend - 1];
}else {
return -1;
}
}
/** Checks whether the circular deque is empty or not. */
public boolean isEmpty() {
return indexend == 0;
}
/** Checks whether the circular deque is full or not. */
public boolean isFull() {
return indexend == deque.length;
}
}