【Lintcode】955. Implement Queue by Circular Array

題目地址:

https://www.lintcode.com/problem/implement-queue-by-circular-array/description

實現循環隊列。題目會初始化一個capacity爲nn的隊列,並保證當隊列滿的時候是不會執行enqueue操作的。

代碼如下:

public class CircularQueue {
    
    int[] arr;
    int size;
    int front, end;
    
    public CircularQueue(int n) {
        // initialize your data structure here
        arr = new int[n];
    }
    /**
     * @return:  return true if the array is full
     */
    public boolean isFull() {
        // write your code here
        return size == arr.length;
    }
    
    /**
     * @return: return true if there is no element in the array
     */
    public boolean isEmpty() {
        // write your code here
        return size == 0;
    }
    
    /**
     * @param element: the element given to be added
     * @return: nothing
     */
    public void enqueue(int element) {
        // write your code here
        arr[end] = element;
        end = (end + 1) % arr.length;
        size++;
    }
    
    /**
     * @return: pop an element from the queue
     */
    public int dequeue() {
        // write your code here
        int res = arr[front];
        front = (front + 1) % arr.length;
        size--;
        return res;
    }
}

所有操作時間複雜度都是O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章