622. Design Circular Queue

LeetCode medium original: C# #array #csharp #design #leetcode #medium #queue #two-pointers
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

Разработайте свою реализацию круговой очереди. Круговая очередь - это линейная структура данных, в которой операции выполняются по принципу FIFO (First In First Out), а последняя позиция соединяется с первой, образуя круг. Одно из преимуществ круговой очереди заключается в том, что мы можем использовать пространство перед очередью. В обычной очереди, когда очередь становится полной, мы не можем вставить следующий element, даже если перед очередью есть свободное место. Но с помощью круговой очереди мы можем использовать пространство для хранения новых значений. 구현 класса MyCircularQueue: MyCircularQueue(k) Инициализирует объект с размером очереди k. int Front() Получает первый element из очереди. Если очередь пуста, returnsся -1. int Rear() Получает последний element из очереди. Если очередь пуста, returnsся -1. boolean enQueue(int value) Вставляет element в циклическую очередь. returns true, если операция прошла успешно. boolean deQueue() Удаляет element из круговой очереди. returns true, если операция выполнена успешно. boolean isEmpty() Проверяет, пуста ли круговая очередь. boolean isFull() Проверяет, заполнена ли круговая очередь. Вы должны решить проблему без использования встроенной структуры данных очереди в вашем языке программирования.

예제:

Input

["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]

[[3], [1], [2], [3], [4], [], [], [], [4], []]

Output

[null, true, true, true, false, 3, true, true, true, 4]

C# 해법

매칭됨/원본
public class MyCircularQueue {
    private int[] queue;
    private int front;
    private int rear;
    private int size;
    private int capacity;
    public MyCircularQueue(int k) {
        queue = new int[k];
        front = 0;
        rear = -1;
        size = 0;
        capacity = k;
    }
    public bool enQueue(int value) {
        if (isFull()) {
            return false;
        }
        rear = (rear + 1) % capacity;
        queue[rear] = value;
        size++;
        return true;
    }
    public bool deQueue() {
        if (isEmpty()) {
            return false;
        }
        front = (front + 1) % capacity;
        size--;
        return true;
    }
    public int Front() {
        return isEmpty() ? -1 : queue[front];
    }
    public int Rear() {
        return isEmpty() ? -1 : queue[rear];
    }
    public bool isEmpty() {
        return size == 0;
    }
    public bool isFull() {
        return size == capacity;
    }
}

C++ 해법

자동 초안, 제출 전 검토
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
public class MyCircularQueue {
    private vector<int>& queue;
    private int front;
    private int rear;
    private int size;
    private int capacity;
    public MyCircularQueue(int k) {
        queue = new int[k];
        front = 0;
        rear = -1;
        size = 0;
        capacity = k;
    }
    public bool enQueue(int value) {
        if (isFull()) {
            return false;
        }
        rear = (rear + 1) % capacity;
        queue[rear] = value;
        size++;
        return true;
    }
    public bool deQueue() {
        if (isEmpty()) {
            return false;
        }
        front = (front + 1) % capacity;
        size--;
        return true;
    }
    public int Front() {
        return isEmpty() ? -1 : queue[front];
    }
    public int Rear() {
        return isEmpty() ? -1 : queue[rear];
    }
    public bool isEmpty() {
        return size == 0;
    }
    public bool isFull() {
        return size == capacity;
    }
}

Java 해법

매칭됨/원본
public class MyCircularQueue {
    private int[] queue;
    private int front;
    private int rear;
    private int size;
    private int capacity;

    public MyCircularQueue(int k) {
        this.queue = new int[k];
        this.front = 0;
        this.rear = -1;
        this.size = 0;
        this.capacity = k;
    }

    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        rear = (rear + 1) % capacity;
        queue[rear] = value;
        size++;
        return true;
    }

    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        front = (front + 1) % capacity;
        size--;
        return true;
    }

    public int Front() {
        return isEmpty() ? -1 : queue[front];
    }

    public int Rear() {
        return isEmpty() ? -1 : queue[rear];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public boolean isFull() {
        return size == capacity;
    }
}

JavaScript 해법

매칭됨/원본
class MyCircularQueue {
    constructor(k) {
        this.queue = Array(k).fill(-1);
        this.front = 0;
        this.rear = -1;
        this.size = 0;
        this.capacity = k;
    }
    
    enQueue(value) {
        if (this.isFull()) {
            return false;
        }
        this.rear = (this.rear + 1) % this.capacity;
        this.queue[this.rear] = value;
        this.size++;
        return true;
    }
    
    deQueue() {
        if (this.isEmpty()) {
            return false;
        }
        this.front = (this.front + 1) % this.capacity;
        this.size--;
        return true;
    }
    
    Front() {
        return this.isEmpty() ? -1 : this.queue[this.front];
    }
    
    Rear() {
        return this.isEmpty() ? -1 : this.queue[this.rear];
    }
    
    isEmpty() {
        return this.size === 0;
    }
    
    isFull() {
        return this.size === this.capacity;
    }
}

Python 해법

매칭됨/원본
class MyCircularQueue:

    def __init__(self, k: int):
        self.queue = [-1] * k
        self.front = 0
        self.rear = -1
        self.size = 0
        self.capacity = k

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        self.rear = (self.rear + 1) % self.capacity
        self.queue[self.rear] = value
        self.size += 1
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        self.front = (self.front + 1) % self.capacity
        self.size -= 1
        return True

    def Front(self) -> int:
        return -1 if self.isEmpty() else self.queue[self.front]

    def Rear(self) -> int:
        return -1 if self.isEmpty() else self.queue[self.rear]

    def isEmpty(self) -> bool:
        return self.size == 0

    def isFull(self) -> bool:
        return self.size == self.capacity

Go 해법

매칭됨/원본
package main

type MyCircularQueue struct {
    queue    []int
    front    int
    rear     int
    size     int
    capacity int
}

func Constructor(k int) MyCircularQueue {
    return MyCircularQueue{
        queue:    make([]int, k),
        front:    0,
        rear:     -1,
        size:     0,
        capacity: k,
    }
}

func (this *MyCircularQueue) enQueue(value int) bool {
    if this.isFull() {
        return false
    }
    this.rear = (this.rear + 1) % this.capacity
    this.queue[this.rear] = value
    this.size++
    return true
}

func (this *MyCircularQueue) deQueue() bool {
    if this.isEmpty() {
        return false
    }
    this.front = (this.front + 1) % this.capacity
    this.size--
    return true
}

func (this *MyCircularQueue) Front() int {
    if this.isEmpty() {
        return -1
    }
    return this.queue[this.front]
}

func (this *MyCircularQueue) Rear() int {
    if this.isEmpty() {
        return -1
    }
    return this.queue[this.rear]
}

func (this *MyCircularQueue) isEmpty() bool {
    return this.size == 0
}

func (this *MyCircularQueue) isFull() bool {
    return this.size == this.capacity
}

Algorithm

Используйте 배열 фиксированного размера для хранения elementов очереди и два указателя: front для отслеживания начала очереди и rear для отслеживания конца очереди.

Реализуйте методы enQueue и deQueue для вставки и удаления elementов, обновляя указатели по круговому принципу.

Реализуйте методы Front, Rear, isEmpty и isFull для доступа к elementам и проверки состояния очереди.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.