[leetcode] Design Circular Queue

임택·2021년 4월 4일
0

알고리즘

목록 보기
59/63

problem

code

1st try: with array

class MyCircularQueue {
    
    class Node {
        int val = -1;
        Node next = null;
        
        public Node(int val) {
            this.val = val;
        }
    }
    
    private int size;
    private int[] q;
    // private Node node;
    private int position;
    
    public MyCircularQueue(int k) {
        size = k;
        position = -1;
        q = new int[k];
        // node = new Node(val);
    }
    
    public boolean enQueue(int value) {
        if (position >= size - 1)
            return false;
                
        q[++position] = value;
        return true;
    }
    
    public boolean deQueue() {
        if (position < 0)
            return false;
        
        int[] temp = new int[size];
        for (int i = 1; i < size; i++) {
            temp[i - 1] = q[i];
        }
        position--;
        q = temp;
        return true;
        
    }
    
    public int Front() {
        if (position < 0) 
            return -1;
        return q[0];
    }
    
    public int Rear() {
        if (position < 0) 
            return -1;
        // System.out.println(q[position]);
        return q[position];
    }
    
    public boolean isEmpty() {
        return position < 0;
    }
    
    public boolean isFull() {
        return position == size - 1;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */

Time: O(N), delete
Space: O(N)

profile
캬-!

0개의 댓글